【问题标题】:I can't change a list to int with map function Python我无法使用映射函数 Python 将列表更改为 int
【发布时间】:2013-09-01 19:21:45
【问题描述】:

我的程序要求用户输入 10 个我正在使用此代码的随机数。

numbers = input("Type 10 numbers, separeted by spaces: ")
numberlist = list(numbers)
numberlist = map(int,numberlist)
print(numberlist)

但是当程序编译时,我可以输入 10 个数字,但我在 shell 中收到了这条消息。

<map object at 0xb51a11cc>

任何人都知道解决方案是什么?我在 ubuntu 13.04 中使用 python 3.3。

谢谢。

【问题讨论】:

  • list(map(int,numberlist)),使用list()。请注意,list(numbers) 不会做你认为它会做的事情,请使用:numbers.split()

标签: python list map int python-3.3


【解决方案1】:

map 在 Python 3.x 中返回一个地图对象,而不是像在 Python 2.x 中那样的列表。要解决此问题,请将地图对象放在此处的列表中:

numberlist = list(map(int,numberlist))

或这里:

print(list(numberlist))

演示:

>>> lis = ['1', '2', '3']
>>> map(int, lis)
<map object at 0x01DE0F70>
>>> list(map(int, lis))
[1, 2, 3]
>>>

此外,您将要执行以下操作以使其正常工作(现在它会尝试将所有空格变成整数,这会爆炸):

numbers = input("Type 10 numbers, separated by spaces: ").split()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 2017-01-31
    相关资源
    最近更新 更多