Python:测试值是否可以在列表理解中转换为int [英] Python: Test if value can be converted to an int in a list comprehension
本文介绍了Python:测试值是否可以在列表理解中转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上我想这样做;
return [ row for row in listOfLists if row[x] is int ]
但是row [x]是一个文本值,可能会或可能不会转换为int
But row[x] is a text value that may or may not be convertible to an int
我知道这可以通过以下方式完成:
I'm aware that this could be done by:
try:
int(row[x])
except:
meh
但是最好只做一次.
有什么想法吗?
推荐答案
If you only deal with integers, you can use str.isdigit()
:
如果字符串中的所有字符都是数字并且至少包含一个字符,则返回true,否则返回false.
Return true if all characters in the string are digits and there is at least one character, false otherwise.
[row for row in listOfLists if row[x].isdigit()]
或者如果可以使用负整数(但应允许):
Or if negative integers are possible (but should be allowed):
row[x].lstrip('-').isdigit()
当然,这只有在没有前导或尾随空白字符(也可以将其删除)时才有效.
And of course this all works only if there are no leading or trailing whitespace characters (which could be stripped as well).
这篇关于Python:测试值是否可以在列表理解中转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文