我有一个这样的列表,名为x(我已经拆分):
['16','bob','2440', '34']
Run Code Online (Sandbox Code Playgroud)
我想编写一个代码来检查是否有任何数字为负数.我试过的代码不起作用.这是我尝试过的:
for num in x:
if num < 0:
print ("Negative number")
Run Code Online (Sandbox Code Playgroud)
您的列表仅包含字符串.所以你应该首先将它们转换为浮点数(或整数,无论你需要什么):
a = ['"16','bob','2440', '-2', '34"']
for x in a:
try:
if float (x) < 0: print ('negative')
except: continue
Run Code Online (Sandbox Code Playgroud)
编辑:我改变int到float如OP是要求数字和不完全的整数.