【问题标题】:How to input Int array in Line in Python [duplicate]如何在Python中的Line中输入Int数组[重复]
【发布时间】:2013-03-21 02:28:29
【问题描述】:

我可以在 Ruby 中使用

   x = gets.split(" ").map{|x| x.to_i}

如何用 Python 编写

【问题讨论】:

    标签: python


    【解决方案1】:
    x = [int(part) for part in input().split()]
    

    在 2.x 中,使用 raw_input() 而不是 input() - 这是因为在 Python 2.x 中,input() 将用户的输入解析为 Python 代码,这既危险又缓慢。 raw_input() 只是给你字符串。在 3.x 中,他们更改了 input() 以按照您通常想要的方式工作。

    这是一个简单的list comprehension,它采用输入的拆分组件(使用str.split(),它在空格上拆分)并使每个组件成为整数。

    【讨论】:

      【解决方案2】:

      在 python 3.x 中

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

      在 python 2.x 中

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

      【讨论】:

      • +1, map() 也是一个非常好的方法。
      【解决方案3】:
      >>> x = raw_input("Int array")
      Int array>? 1 2 3
      >>> map(int, x.split())
      [1, 2, 3]
      

      【讨论】:

        猜你喜欢
        • 2020-08-04
        • 2013-05-07
        • 2013-11-06
        • 2021-11-11
        • 1970-01-01
        • 2011-12-12
        • 2019-09-17
        • 2015-02-12
        • 2021-01-17
        相关资源
        最近更新 更多