Chr*_*ung 22 python string integer list
我有一个包含字符串格式的数字和字母的列表.
mylist=['1','orange','2','3','4','apple']
Run Code Online (Sandbox Code Playgroud)
我需要提出一个只包含数字的新列表:
mynewlist=['1','2','3','4']
Run Code Online (Sandbox Code Playgroud)
如果我有办法检查列表中的每个项目是否可以转换为Integer,我应该能够通过执行以下操作来提出我想要的内容:
for item in mylist:
if (check item can be converted to integer):
mynewlist.append(item)
Run Code Online (Sandbox Code Playgroud)
如何检查字符串是否可以转换为整数?或者有更好的方法吗?
ars*_*jii 33
试试这个:
mynewlist = [s for s in mylist if s.isdigit()]
Run Code Online (Sandbox Code Playgroud)
来自文档:
str.isdigit()如果字符串中的所有字符都是数字并且至少有一个字符,则返回true,否则返回false.
对于8位字符串,此方法取决于区域设置.
如注释中所述,isdigit()返回True并不一定表示字符串可以通过int()函数解析为int ,并且返回False并不一定表示它不能.然而,上述方法应该适用于您的情况.
Mik*_*ler 13
快速,简单,但可能并不总是正确的:
>>> [x for x in mylist if x.isdigit()]
['1', '2', '3', '4']
Run Code Online (Sandbox Code Playgroud)
如果你需要获得数字更传统:
new_list = []
for value in mylist:
try:
new_list.append(int(value))
except ValueError:
continue
Run Code Online (Sandbox Code Playgroud)
注意:结果有整数.如果需要,将它们转换回字符串,将上面的行替换为:
try:
new_list.append(str(int(value)))
Run Code Online (Sandbox Code Playgroud)
Ash*_*ary 10
您可以使用异常处理,因为str.digit它只适用于整数,并且也可能因此而失败:
>>> str.isdigit(' 1')
False
Run Code Online (Sandbox Code Playgroud)
使用生成器功能:
def solve(lis):
for x in lis:
try:
yield float(x)
except ValueError:
pass
>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> list(solve(mylist))
[1.0, 2.0, 3.0, 4.0, 1.5, 2.6] #returns converted values
Run Code Online (Sandbox Code Playgroud)
或者你可能想要这个:
def solve(lis):
for x in lis:
try:
float(x)
return True
except:
return False
...
>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> [x for x in mylist if solve(x)]
['1', '2', '3', '4', '1.5', '2.6']
Run Code Online (Sandbox Code Playgroud)
或使用ast.literal_eval,这适用于所有类型的数字:
>>> from ast import literal_eval
>>> def solve(lis):
for x in lis:
try:
literal_eval(x)
return True
except ValueError:
return False
...
>>> mylist=['1','orange','2','3','4','apple', '1.5', '2.6', '1+0j']
>>> [x for x in mylist if solve(x)]
['1', '2', '3', '4', '1.5', '2.6', '1+0j']
Run Code Online (Sandbox Code Playgroud)
检查通常的方式是否东西可以转化为int对try一下,看看,下面的EAFP原则:
try:
int_value = int(string_value)
except ValueError:
# it wasn't an int, do something appropriate
else:
# it was an int, do something appropriate
Run Code Online (Sandbox Code Playgroud)
所以,在你的情况下:
for item in mylist:
try:
int_value = int(item)
except ValueError:
pass
else:
mynewlist.append(item) # or append(int_value) if you want numbers
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,围绕一些以 结尾的琐碎代码的循环mynewlist.append(item)可以变成列表推导式、生成器表达式或对mapor 的调用filter。但是在这里,您不能,因为无法将try/except放入表达式中。
但是如果你把它包装在一个函数中,你可以:
def raises(func, *args, **kw):
try:
func(*args, **kw)
except:
return True
else:
return False
mynewlist = [item for item in mylist if not raises(int, item)]
Run Code Online (Sandbox Code Playgroud)
……或者,如果您愿意:
mynewlist = filter(partial(raises, int), item)
Run Code Online (Sandbox Code Playgroud)
以这种方式使用它更干净:
def raises(exception_types, func, *args, **kw):
try:
func(*args, **kw)
except exception_types:
return True
else:
return False
Run Code Online (Sandbox Code Playgroud)
这样,您可以将期望的异常(或异常元组)传递给它,这些异常将返回True,但如果引发任何意外异常,它们将传播出去。所以:
mynewlist = [item for item in mylist if not raises(ValueError, int, item)]
Run Code Online (Sandbox Code Playgroud)
......会做你想做的,但是:
mynewlist = [item for item in mylist if not raises(ValueError, item, int)]
Run Code Online (Sandbox Code Playgroud)
... 将提高 a TypeError,它应该。
| 归档时间: |
|
| 查看次数: |
75841 次 |
| 最近记录: |