我在将一线循环以下转换为多线循环时遇到麻烦。这是原始代码:
sequences = [[[item.strip() for item in itemset.split(",")] for itemset in sequence] for sequence in sequences]
我尝试过的多行循环:
for sequence in sequences:
for itemset in sequence:
for item in itemset.split(","):
sequences.append(item.strip())
它与原始版本不兼容。有想法吗?
答案 0 :(得分:2)
您原来的问题会使用相同的数据名称(sequences
)重新分配结果。在这里,我将结果分配给变量result
。
鉴于您未提供示例数据,我只是做了一些(sequences
)。
您原来的列表理解是嵌套的(请注意方括号),每一层都创建一个单独的列表。
[[[x.strip() for x in something] for something in something_else] for something_else in sequences]
。
我通过为每个for-loop
创建一个新列表来重新创建该结构,并随其添加以匹配原始列表理解。
# Sample data.
sequences = [['the, quick, brown fox'], ['jumped, over, the lazy dog']]
# Solution.
result = []
for sequence in sequences:
inner_list = list()
result.append(inner_list)
for itemset in sequence:
inner_list_2 = list()
inner_list.append(inner_list_2)
for item in itemset.split(","):
inner_list_2.append(item.strip())
>>> result
[[['the', 'quick', 'brown fox']], [['jumped', 'over', 'the lazy dog']]]
# Original list comprehension.
>>> [[[item.strip() for item in itemset.split(",")]
for itemset in sequence]
for sequence in sequences]
[[['the', 'quick', 'brown fox']], [['jumped', 'over', 'the lazy dog']]]