我的列表= [['A B','A B C','A B C D'],['C','D E F','A B']]
如何获得类似以下的列表:myli = [['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)):
x.extend(item[i].split())
myli.append(x)
最佳答案
您需要在外部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)