繁体   English   中英

将列表中的项目转换为具有特定条件的 int (Python)

[英]Converting items in list to int with specific condition (Python)

我有一个由字符组成的字符串,所有字符都用逗号分隔,我想创建一个仅包含整数的列表。 我写:

str = '-4,, 5, 170.5,4,s, k4, 4k, 1.3,  ,, 8'.replace(' ','')
# Now the str without spaces: '-4,,5,170.5,4,s,k4,4k,1.3,,,8'

lst_str = [item for item in str.split(',')
# Now I have a list with the all items: ['-4', '5', '170.5', '4' ,'s', 'k4' ,'4k', '1.3', '8']

int_str = [num for num in lst_str if num.isdigit]
# The problem is with negative character and strings like '4k'
# and 'k4' which I don't want, and my code doesn't work with them.

#I want this: ['-4', '5', '4', '8'] which I can changed after any item to type int.

有人可以帮我怎么做吗? 无需导入任何 class。 我没有找到这个特定问题的答案(这是我的第一个问题)

isdigit()是 function,而不是属性。 应该用()调用它。 它也不适用于负数,您可以删除检查的减号

int_str = [num for num in lst_str if num.replace('-', '').isdigit()]
# output: ['-4', '5', '4', '8']

如果您需要避免出现'-4-'的情况,请使用出现次数参数

num.replace('-', '', 1)

尝试这个:

def check_int(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False
    
int_str = [num for num in lst_str if check_int(num)]

我是这样做的:

string = '-400,, 5, 170.5,4,s, k4, 4k, 1.3,  ,, 8'.replace(' ','')
# Now the str without spaces: '-4,,5,170.5,4,s,k4,4k,1.3,,,8'

let_str = [item for item in string.split(',')]
# Now I have a list with the all items: ['-4', '5', '170.5', '4' ,'s', 'k4' ,'4k', '1.3', '8']
neg_int = [num for num in let_str if "-" in num]

int_str = [num for num in let_str if num.isdigit()]
neg_int = [num for num in neg_int if num[1:].isdigit()]

for num in neg_int: int_str.append(num)
print(int_str)

这非常接近问题Python - 如何仅将混合列表中的数字转换为浮点数? 如果将它与python 结合使用:从混合列表中提取整数

您的“过滤器”根本不过滤-名为num的非空字符串实例上的 function num.isdigit始终为真。

您使用整数而不是浮点数:创建一个 function 尝试将某些内容解析为整数,如果不返回 None。 只保留那些不是 None 的。

text  = '-4,, 5, 170.5,4,s, k4, 4k, 1.3,  ,, 8'    
cleaned = [i.strip() for i in text.split(',') if i.strip()]

def tryParseInt(s):
    """Return integer or None depending on input."""
    try:
        return int(s)
    except ValueError:
        return None

# create the integers from strings that are integers, remove all others 
numbers = [tryParseInt(i) for i in cleaned if tryParseInt(i) is not None]

print(cleaned)
print(numbers)

Output:

['-4', '5', '170.5', '4', 's', 'k4', '4k', '1.3', '8']
[-4, 5, 4, 8]

正则表达式解决方案怎么样:

import re

str = '-4,, 5, 170.5,4,s, k4, 4k, 1.3,  ,, 8'
int_str = [num for num in re.split(',\s*', str) if re.match(r'^-?\d+$', num)]

您可以尝试用这个 function 替换 num.isdigit:

def isNumber(str):
    try:
        int(str)
        return True
    except:
        return False

示例: int_str = [num for num in lst_str if isNumber(num)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM