作为参考,这是一种正则表达式方法。这可能是矫枉过正。
mylist = ['0', 'Negate', '-3', '2', 'SPECIALCASE', '3']
import re
p = re.compile(r'-?\d+')
[p.match(e) is not None for e in mylist]
# returns [True, False, True, True, False, True]
这将返回一个列表,其中包含True可选地以 a 开头的任何字符串-,然后包含一个或多个数字;False对于任何其他字符串。
或者,如果您不需要列表但只想执行不同的操作:
for item in mylist:
if p.match(item):
# it's a number
else:
# it's a string
The above works becasue None (i.e. no match) evaluates to False and anything else (when it comes to regex matches) evaluates to True. If you want to be more explicit you can use if p.match(item) is not None:.