Python map()函数

时间:2014-09-03 12:48:30

标签: python map-function

为什么我在以下代码中遇到map()函数错误?为什么无法映射转换列表x中的否定数字。输出应该像" 1 - > 2 - > 3&#34 ;.每当我输入-999时,列表应该结束。我收到的错误如下:

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]),

3 个答案:

答案 0 :(得分:1)

谢谢......得到了它:)

    x=[]
    while(1):
       s=raw_input("Input a number\n(type -999 to end);")
       s=int(s)
       x.append(s)
       if s<0:
          break
       pass
    print "\n%d" %(x[0]),
    for i in range(1,(len(x))):
        print "-->%d" %(x[i]),
    print "\n\nNumber of items = %d" %(len(x)-1)

答案 1 :(得分:0)

尝试

x = map(int,raw_input().split())

答案 2 :(得分:0)

没有解决与地图无关的其他错误,问题是地图会返回一个列表。

在IDLE中查看:

>>> map(int, ["123", "456", 7.3])
[123, 456, 7]
>>>

所以x<0毫无意义,你会想要像min(x)&lt; 0.将列表作为输入的东西。

在这种情况下,您可能应该单独隔离和处理每个条目。获取输入行,在其中扫描空格(或split(),如下所示)并解析每个整数。

即使你正确地使用了split和map,你也会自动使用-999处理同一行的整数,但是在它之后。任何不解析的东西都不会给你足够的反馈,知道到底出了什么问题。

解析用户输入通常必须是低级别和面向字符的,否则无法诊断其错误输入。有时候生活很乏味。

(另外,为什么清空列表然后尝试打印?)