Mylists = [[' A B',' AB C',' ABC D'],[' C',&# 39; DE F',' A B']]
如何获得如下列表:myli = [[' A',' B',' A'' B' ' C'' A'' B',' C'' d'],[&# 39; C'' d'' E'' F'' A'' B&#39 ;]]
这是我的代码:
x = []
myli = []
for item in Mylists:
for i in range(len(item)):
x.extend(item[i].split())
myli.append(x)
答案 0 :(得分:2)
你需要在外部forloop中初始化x。
您的代码
Mylists = [['A B','A B C','A B C D'],['C','D E F','A B']]
x = []
myli = []
for item in Mylists:
for i in range(len(item)):
# BUG: since x is not reinitialized, it contains the same old
# memory address that was appended to myli
# extending x means you are modifying the x that you previously appended to myli
# infact, every appended x is the same x !
x.extend(item[i].split())
# appending the same old x, which will inevitably be modified
# in the next iteration
myli.append(x)
校正
Mylists = [['A B','A B C','A B C D'],['C','D E F','A B']]
myli = []
for item in Mylists:
x = [] # reinitialize x
for i in range(len(item)):
x.extend(item[i].split())
myli.append(x)
答案 1 :(得分:0)
假设mylist
是字符串列表的列表,其中单词用空格分隔:
ml = [['A B','A B C','A B C D'],['C','D E F','A B']]
l = []
for inner in ml:
newinner = []
for innerstr in inner:
for word in innerstr.split(' ')
newinner.append(word)
l.append(newinner)