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 
awesoon
  • 30,028
  • 9
  • 67
  • 92
user793468
  • 4,728
  • 22
  • 78
  • 124
  • possible duplicate of [Flattening a shallow list in Python](http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python) – awesoon Jul 14 '15 at 03:44

2 Answers2

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))
Paul Rooney
  • 19,499
  • 9
  • 39
  • 60
0
sum([row.strip().split('\t') for row in rows],[])

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

NightShadeQueen
  • 3,174
  • 3
  • 22
  • 36