使用特定条件将列表中的项转换为int(Python)

使用特定条件将列表中的项转换为int(Python),python,list,integer,conditional-statements,Python,List,Integer,Conditional Statements,我有一个由字符组成的字符串,所有字符都被逗号分割,我想创建一个只包含整数的列表。我写道: 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 item

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

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.
有人能帮我怎么做吗?不导入任何类。 我没有找到这个特定问题的答案(这是我的第一个问题)

试试这个:

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)]
试试这个:

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)]
isdigit()
是一个函数,而不是属性。应该使用
()
调用它。它对负数也不起作用,你可以去掉负号

int_str = [num for num in lst_str if num.replace('-', '').isdigit()]
# output: ['-4', '5', '4', '8']
如果需要避免出现
'-4-'
的情况,请使用出现次数参数

num.replace('-', '', 1)
isdigit()
是一个函数,而不是属性。应该使用
()
调用它。它对负数也不起作用,你可以去掉负号

int_str = [num for num in lst_str if num.replace('-', '').isdigit()]
# output: ['-4', '5', '4', '8']
如果需要避免出现
'-4-'
的情况,请使用出现次数参数

num.replace('-', '', 1)
我是这样做的:

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)
我是这样做的:

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)

如果你把它与这个问题结合起来,这就非常接近了

您的“筛选器”根本不进行筛选-名为
num
的非空字符串实例上的函数
num.isdigit
始终为true

使用int代替float:创建一个函数,如果不返回None,则尝试将某些内容解析为int。 只保留那些没有的

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)
输出:

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

如果你把它与这个问题结合起来,这就非常接近了

您的“筛选器”根本不进行筛选-名为
num
的非空字符串实例上的函数
num.isdigit
始终为true

使用int代替float:创建一个函数,如果不返回None,则尝试将某些内容解析为int。 只保留那些没有的

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)
输出:

['-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)]

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

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)]

您可以尝试用以下函数替换num.isdigit:

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

示例:
int\u str=[num for num in lst\u str if isNumber(num)]
您可以尝试用以下函数替换num.isdigit:

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

示例:
int\u str=[num代表lst\u str中的num,如果isNumber(num)]

在EAFP之后,您可以编写一个函数,通过调用
int
str
转换为
int
,并将异常处理为
None
s,然后从EAFP中过滤出来。您可以编写一个函数,通过调用
int
并进行处理,将
str
转换为
int
例如
None
s等异常,然后将其过滤掉谢谢!这是目前对我最好的:)谢谢你!这是目前对我最好的:)