【发布时间】:2021-07-21 14:21:07
【问题描述】:
我有一个由字符组成的字符串,所有字符都用逗号分隔,我想创建一个仅包含整数的列表。我写道:
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.
有人可以帮我怎么做吗?无需导入任何类。 我没有找到这个特定问题的答案(这是我的第一个问题)
【问题讨论】:
-
在 EAFP 之后,您可以编写一个将
str转换为int的函数,方法是调用int并处理像Nones 这样的异常,然后过滤掉它们
标签: python list integer conditional-statements