【问题标题】:Input int list in Python 3 [duplicate]在 Python 3 中输入 int 列表 [重复]
【发布时间】:2013-05-07 16:19:36
【问题描述】:

我尝试从 Python 2.7 更改为 3.3.1

我要输入

1 2 3 4

并输出

[1,2,3,4]

在 2.7 中我可以使用

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

我应该在 Python 3.x 中使用什么?

【问题讨论】:

    标签: python string list python-3.x


    【解决方案1】:

    在 Python 3 中使用 input()raw_input 在 Python 3 中已重命名为 inputmap 现在返回一个迭代器而不是列表。

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

    或:

    score = list(map(int, input().split()))
    

    【讨论】:

      【解决方案2】:

      作为一般规则,您可以使用 Python 附带的 2to3 tool 至少为您指明正确的移植方向:

      $ echo "score = map(int, raw_input().split())" | 2to3 - 2>/dev/null
      --- <stdin> (original)
      +++ <stdin> (refactored)
      @@ -1,1 +1,1 @@
      -score = map(int, raw_input().split())
      +score = list(map(int, input().split()))
      

      输出不一定是惯用的(列表理解在这里更有意义),但它会提供一个不错的起点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-04
        • 2017-03-22
        • 2013-03-21
        • 2021-11-11
        • 2019-09-17
        • 2019-04-05
        相关资源
        最近更新 更多