Python 如何在列表中创建列表,其中未来的每个列表都由列表中的空格分隔

Python 如何在列表中创建列表,其中未来的每个列表都由列表中的空格分隔,python,string,python-3.x,list,input,Python,String,Python 3.x,List,Input,用户使用空格提供输入: row = list(input()) print(row) ['1','2','3',' ','4','5','6',' ','7','8','9',' '] 所以我需要在下面创建“行”列表。列表根据空格分为子列表: [['1','2','3'],['4','5','6'],['7','8','9']] myinput = '123 456 789' row = list(map(list, myinput.split())) print(row) [['1

用户使用空格提供输入:

row = list(input())

print(row)

['1','2','3',' ','4','5','6',' ','7','8','9',' ']
所以我需要在下面创建“行”列表。列表根据空格分为子列表:

[['1','2','3'],['4','5','6'],['7','8','9']]
myinput = '123 456 789'
row = list(map(list, myinput.split()))

print(row)

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

您可以使用
str.split
按空格分割:

[['1','2','3'],['4','5','6'],['7','8','9']]
myinput = '123 456 789'
row = list(map(list, myinput.split()))

print(row)

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
或者,使用列表理解:

row = [list(i) for i in myinput.split()]
可以使用拆分空格上的输入,以提供子字符串列表

例如,
'123456789'
将变成
['123','456','789']

然后使用
list()
构造函数将这些字符串转换为字符列表(您已经熟悉)

制定最终代码:

row = [list(s) for s in input().split()]
#[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

从列表而不是字符串开始,可以使用以下方法:

我们根据值是否为空格对其进行分组,只保留非空格组成的组。

尝试以下操作:

abc=['1','2','3',' ','4','5','6',' ','7','8','9',' ']
newList=list()
temp=list()
for i in abc:
    if(i==' '):
      newList.append(temp)
      temp=list()
    else:
      temp.append(i)
print(newList)
输出:

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

为SNIPPETI添加输入示例,考虑列表理解更可读,但这是完成的工作:)+ 1代码> GROPBY(行,STRISISDIGH)或<代码> STRISISSUL< <代码> >代码>如果不是键