首页 > 解决方案 > 将整数添加到列表中,同时将由空格分隔的数字字符串转换为整数

问题描述

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

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']]

标签: pythonpython-3.x

解决方案


代替

Data.append(added)

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

然后

1
22
2 3 4

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

推荐阅读