【问题标题】:how would I convert an input of space separated numbers into a list如何将空格分隔数字的输入转换为列表
【发布时间】:2022-08-11 01:32:33
【问题描述】:

非常基本的问题,但是我如何将给定的空格分隔数字输入更改为列表: 例如

t = input(\"Enter some numbers: \")
# for example sake the user inputs: 4 5 10 9 8
# I want to then convert these numbers into a list of [4, 5, 10, 9, 8]

    标签: python


    【解决方案1】:

    您可以使用str.split() 将字符串拆分为列表并转换为int。

    t = "4 5 10 9 8"  # equivalent to t = input("Enter some numbers: ") with 4 5 10 9 8
    print([int(v) for v in t.split(" ")])  # [4, 5, 10, 9, 8]
    

    【讨论】:

      【解决方案2】:

      将所有字符串输入数字转换为整数:

      # s is what you have from input()
      numbers = [int(x) for x in s.split() ]
      
      # later to print all in a line
      print(*numbers) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-20
        • 2020-03-31
        • 1970-01-01
        • 1970-01-01
        • 2016-03-12
        相关资源
        最近更新 更多