Python 检查列表项是否为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16908186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python check if list items are integers?
提问by Chris Aung
I have a list which contains numbers and letters in string format.
我有一个包含字符串格式的数字和字母的列表。
mylist=['1','orange','2','3','4','apple']
I need to come up with a new list which only contains numbers:
我需要想出一个只包含数字的新列表:
mynewlist=['1','2','3','4']
If I have a way to check if each item in list can be converted to Integer, I should be able to come up with what I want by doing something like this:
如果我有办法检查列表中的每个项目是否可以转换为整数,我应该能够通过执行以下操作来想出我想要的:
for item in mylist:
if (check item can be converted to integer):
mynewlist.append(item)
How do I check that a string can be converted to an integer? Or is there any better way to do it?
如何检查字符串是否可以转换为整数?或者有没有更好的方法来做到这一点?
采纳答案by arshajii
Try this:
尝试这个:
mynewlist = [s for s in mylist if s.isdigit()]
From the docs:
从文档:
str.isdigit()Return true if all characters in the string are digits and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
str.isdigit()如果字符串中的所有字符都是数字并且至少有一个字符,则返回 true,否则返回 false。
对于 8 位字符串,此方法取决于语言环境。
As noted in the comments, isdigit()returning Truedoes not necessarily indicate that the string can be parsed as an int via the int()function, and it returning Falsedoes not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.
正如评论中所指出的,isdigit()返回True并不一定表示可以通过int()函数将字符串解析为 int ,并且它返回False并不一定表示它不能。尽管如此,上述方法应该适用于您的情况。
回答by Mike Müller
Fast, simple, but maybe not always right:
快速、简单,但可能并不总是正确的:
>>> [x for x in mylist if x.isdigit()]
['1', '2', '3', '4']
More traditional if you need to get numbers:
如果您需要获取数字,则更传统:
new_list = []
for value in mylist:
try:
new_list.append(int(value))
except ValueError:
continue
Note: The result has integers. Convert them back to strings if needed, replacing the lines above with:
注意:结果为整数。如果需要,将它们转换回字符串,将上面的行替换为:
try:
new_list.append(str(int(value)))
回答by Ashwini Chaudhary
You can use exceptional handling as str.digitwill only work for integers and can fail for something like this too:
您可以使用异常处理,因为它str.digit仅适用于整数,并且也可能因以下情况而失败:
>>> str.isdigit(' 1')
False
Using a generator function:
使用生成器函数:
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
or may be you wanted this:
或者你可能想要这个:
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']
or using ast.literal_eval, this will work for all types of numbers:
或使用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']
回答by abarnert
The usual way to check whether something can be converted to an intis to tryit and see, following the EAFPprinciple:
检查通常的方式是否东西可以转化为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
So, in your case:
所以,在你的情况下:
for item in mylist:
try:
int_value = int(item)
except ValueError:
pass
else:
mynewlist.append(item) # or append(int_value) if you want numbers
In most cases, a loop around some trivial code that ends with mynewlist.append(item)can be turned into a list comprehension, generator expression, or call to mapor filter. But here, you can't, because there's no way to put a try/exceptinto an expression.
在大多数情况下,围绕一些以 结尾的琐碎代码的循环mynewlist.append(item)可以变成列表推导式、生成器表达式或对mapor 的调用filter。但是在这里,您不能,因为无法将try/except放入表达式中。
But if you wrap it up in a function, you can:
但是如果你把它包装在一个函数中,你可以:
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)]
… or, if you prefer:
……或者,如果您愿意:
mynewlist = filter(partial(raises, int), item)
It's cleaner to use it this way:
以这种方式使用它更干净:
def raises(exception_types, func, *args, **kw):
try:
func(*args, **kw)
except exception_types:
return True
else:
return False
This way, you can pass it the exception (or tuple of exceptions) you're expecting, and those will return True, but if any unexpectedexceptions are raised, they'll propagate out. So:
这样,您可以将期望的异常(或异常元组)传递给它,这些异常将返回True,但如果引发任何意外异常,它们将传播出去。所以:
mynewlist = [item for item in mylist if not raises(ValueError, int, item)]
… will do what you want, but:
......会做你想做的,但是:
mynewlist = [item for item in mylist if not raises(ValueError, item, int)]
… will raise a TypeError, as it should.
... 将提高 a TypeError,它应该。

