Bol*_*ter 20 python int types casting
基本上我想这样做;
return [ row for row in listOfLists if row[x] is int ]
Run Code Online (Sandbox Code Playgroud)
但是row [x]是一个文本值,可以转换为int,也可以不转换为int
我知道这可以通过以下方式完成:
try:
int(row[x])
except:
meh
Run Code Online (Sandbox Code Playgroud)
但做它是一个单行的很好.
有任何想法吗?
Fel*_*ing 29
如果只处理整数,可以使用str.isdigit():
如果字符串中的所有字符都是数字并且至少有一个字符,则返回true,否则返回false.
[row for row in listOfLists if row[x].isdigit()]
Run Code Online (Sandbox Code Playgroud)
或者如果可能是负整数(但应该允许):
row[x].lstrip('-').isdigit()
Run Code Online (Sandbox Code Playgroud)
当然,只有在没有前导或尾随空格字符(也可以被剥离)时,这一切都有效.