获取用户输入的数字列表

新手上路,请多包涵

我尝试使用 input (Py3) / raw_input() (Py2) 来获取数字列表,但是使用代码

numbers = input()
print(len(numbers))

the input [1,2,3] and 1 2 3 gives a result of 7 and 5 respectively – it seems to interpret the input as if it were a string .有什么直接的方法可以列出清单吗?也许我可以使用 re.findall 来提取整数,但如果可能的话,我更愿意使用更 Pythonic 的解决方案。

原文由 Underyx 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 750
2 个回答

在 Python 3.x 中,使用它。

 a = [int(x) for x in input().split()]

例子

>>> a = [int(x) for x in input().split()]
3 4 5
>>> a
[3, 4, 5]
>>>

原文由 greentec 发布,翻译遵循 CC BY-SA 3.0 许可协议

解析由空格分隔的数字列表比尝试解析 Python 语法要容易得多:

蟒蛇 3:

 s = input()
numbers = list(map(int, s.split()))

蟒蛇2:

 s = raw_input()
numbers = map(int, s.split())

原文由 Sven Marnach 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题