简体   繁体   English

一行循环到多行python

[英]One line for loop to multiple lines python

I've got trouble reverting below one line loop to multiple lines loop. 我无法将一行循环恢复到多行循环。 here is the original code: 这是原始代码:

sequences = [[[item.strip() for item in itemset.split(",")] for itemset in sequence] for sequence in sequences]

Multiple line loop that I tried: 我试过多行循环:

for sequence in sequences:
 for itemset in sequence:
    for item in itemset.split(","):
       sequences.append(item.strip())

It does not work as the original one. 它不像原来的那样工作。 Any idea? 任何想法?

Your original question reassigns the result with the same name of the data ( sequences ). 您的原始问题会使用相同的数据名称( sequences )重新分配结果。 Here, I assign the result to the variable result . 在这里,我将结果分配给变量result

Given that you did not provide sample data, I just made some up ( sequences ). 鉴于您没有提供样本数据,我只是做了一些( sequences )。

Your original list comprehension is nested (note the brackets), with each layer creating a separate list. 您的原始列表理解是嵌套的(注意括号),每个层创建一个单独的列表。

[[[x.strip() for x in something] for something in something_else] for something_else in sequences] . [[[x.strip() for x in something] for something in something_else] for something_else in sequences]

I've recreated that structure by creating a new list with each for-loop , appending as it goes along to match the original list comprehension. 我通过创建一个包含每个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']]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM