【问题标题】:Adding integers to list, while making strings of numbers separated by space into integers将整数添加到列表中,同时将由空格分隔的数字字符串转换为整数
【发布时间】:2021-03-13 08:40:31
【问题描述】:

我目前正在尝试追加整数和字符串,我正在尝试将其转换为整数,因为它们只能是用空格分隔的数字。 我当前的代码:

def check(x):
    if type(x) == str:
        x = x.split()
        return x
    else:
        return x

Data = []
while True:
    try:
        numbers = input()
        if numbers !='':
            added = check(numbers)
            Data.append(added)
        else:
            print(Data)
            break
    except EOFError as error:
        print(Data)
        break

但这并不完全符合我的需要。 例如

的输入
   1
   22
   1 2 3

给我输出

   [['1'], ['22'], ['2', '3', '4']]

虽然我想要输出

[['1'], ['22'], ['2'], ['3'], ['4']]

【问题讨论】:

  • 欢迎来到 StackOverflow。您的示例输入与您想要的输出不匹配。 (输入为 1 2 3,但输出为 2 3 4。)请您编辑您的问题吗?

标签: python python-3.x


【解决方案1】:

替换

Data.append(added)

for d in added:
    Data.append([d])

然后

1
22
2 3 4

[['1'], ['22'], ['2'], ['3'], ['4']]

【讨论】:

    【解决方案2】:

    上面的代码很好,但这段代码也可以帮助你完成任务

    Data = []
    while True:
      try:
        numbers = list(map(int,input().split()))
        if len(numbers)==0:
          print(Data)
          break
        else:
          Data.append(numbers)
      except:
        print(Data)
    

    当我们提供输入时也是如此

    2
    22
    1 2 3 4
    

    当您不提供任何输入(例如简单的输入)时,将打破无限循环,然后为您提供以下输出!。我认为这个功能真的是多余的! 输出是

    [[2],[22],[1,2,3,4]]
    

    希望这会有所帮助!快乐学习:)

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 1970-01-01
      • 2013-11-02
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      相关资源
      最近更新 更多