如何测试列表中的每个项目是否都是“int”类型?
假设我有一个数字列表。我该如何检查列表中的每个项目都是 int?
我四处搜寻,但没有找到任何与此相关的信息。
for i in myList:
result=isinstance(i, int)
if result == False:
break
可以,但在我看来看起来非常丑陋且不符合Python风格。
有没有更好的(并且更Pythonic)的方法来做到这一点?
Say I have a list of numbers. How would I do to check that every item in the list is an int?
I have searched around, but haven't been able to find anything on this.
for i in myList:
result=isinstance(i, int)
if result == False:
break
would work, but looks very ugly and unpythonic in my opinion.
Is there any better(and more pythonic) way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
有几种不同的方法可以做到这一点。例如,如果您的列表仅包含数字:
无论如何,如果您的列表包含布尔值,此解决方案将无法按预期工作,正如 @merlin 所说:
如果您的列表包含布尔值,您应该使用
type
而不是isinstance
(它有点慢,但可以按您的预期工作):There are a few different ways to do it. For example, if your list includes only numbers:
Anyways, this solution doesn't work as expected if your list includes booleans, as remarked by @merlin:
If your list include booleans you should use
type
instead ofisinstance
(it' a little slower, but works as you expect):以下语句应该有效。它使用
any
内置函数和生成器表达式:如果列表中存在非 int,则返回 true。例如:
all
内置函数也可以完成相同的任务,有些人可能会认为它更有意义(请参阅 德拉甘的答案)The following statement should work. It uses the
any
builtin and a generator expression:This will return true if there is a non-int in the list. E.g.:
The
all
builtin could also accomplish the same task, and some might argue it is makes slightly more sense (see Dragan's answer)一种方法不是测试,而是坚持。这意味着你的程序可以智能地处理更广泛的输入——如果有人向它传递一个浮点数,它就不会失败。
或(就地):
如果某些内容无法转换,它将引发异常,如果您愿意,您可以捕获该异常。
One approach would not be to test, but to insist. This means your program can handle a broader range of inputs intelligently -- it won't fail if someone passes it a float instead.
or (in-place):
If something can't be converted, it will throw an exception, which you can then catch if you care to.
查看函数
然后调用
See functions
Then call
发现自己有同样的问题,但在不同的情况下:如果列表中的“整数”表示为字符串(例如,在一行整数和字符串上使用“line.split()”后我的情况就是这样读取文本文件),并且您只想检查列表的元素是否可以表示为整数,您可以使用:
例如:
Found myself with the same question but under a different situation: If the "integers" in your list are represented as strings (e.g., as was the case for me after using 'line.split()' on a line of integers and strings while reading in a text file), and you simply want to check if the elements of the list can be represented as integers, you can use:
For example: