1

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?

3
  • 2
    How about some sample data for testing purposes? Commented Oct 4, 2018 at 1:54
  • Also, review PEP8 for your indentation there. python.org/dev/peps/pep-0008 Commented Oct 4, 2018 at 1:55
  • 1
    you should not reuse sequences, create another empty list and append to it every loop Commented Oct 4, 2018 at 2:00

1 Answer 1

3

Your original question reassigns the result with the same name of the data (sequences). Here, I assign the result to the variable result.

Given that you did not provide sample data, I just made some up (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].

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.

# 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']]]
Sign up to request clarification or add additional context in comments.

4 Comments

Not quite the same result as running the original on those sequences: [[['the', 'quick', 'brown fox']], [['jumped', 'over', 'the lazy dog']]] You need another array.
Agreed. I've amended the original to include it.
where do we need to add another array?
My original reply returned [['the', 'quick', 'brown fox'], ['jumped', 'over', 'the lazy dog']], which was missing one level of nesting and therefore did not match the answer you get from the list comprehension you provided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.