为什么我在下面的代码中使用map()函数发生错误?为什么不能在名单x
中映射转换负数。输出应该像“1 - > 2 - > 3”。只要我输入-999
,该列表就应该结束。我得到一个错误,如:Python map()函数
Traceback (most recent call last):
File "c2.py", line 3, in <module>
x=map(int,x)
ValueError: invalid literal for int() with base 10: '-'
代码:
while(1):
x=list(raw_input("Input a number\n(type -999 to end);"))
x=map(int,x)
if x<0:
break
pass
print x
del x[len(x)]
for i in range(0,(len(x))):
print "%d-->" %(x[i]),
'INT(X)'的确会转换'x'到一个整数,不需要'map';但如果'x'是一个列表则不会。所以你也应该删除第二行的'list'调用。 – Kevin 2014-09-03 12:52:11
输入格式应采用何种格式? ''1 2 3 4 -999“'在一条线上,还是单独的输入?注意'list(“ - 999”)== [' - ','9','9','9']'。 – jonrsharpe 2014-09-03 12:52:59
由于'raw_input'返回一个字符串,'list(raw_input(...))'会将该字符串分解为包含原始字符串的字符的列表。 – chepner 2014-09-03 12:58:08