0

Unable to transform the following nested for loop to a list comprehension:

for row in rows:
    elements = row.strip().split('\t')
    for element in elements:
        print(element)

Input Data is tab delimited:

ola    olb    olc    old
ole    olf    olg    olh
oli    olj    olk    olk
oll    olm    oln    ooo 

Desired Output:

ola
olb    
olc    
old
ole    
olf    
olg    
olh
oli    
olj    
olk    
olk
oll    
olm    
oln    
ooo 
1

2 Answers 2

2

Like this

with open('tabdelim.txt') as rows:
    lstcmp = [item for row in rows for item in row.strip().split('\t')]
    print('\n'.join(lstcmp))
Sign up to request clarification or add additional context in comments.

Comments

0
sum([row.strip().split('\t') for row in rows],[])

The builtin sum is very useful for flattening a list of lists.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.