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
  • 32,469
  • 11
  • 74
  • 99
user793468
  • 4,898
  • 23
  • 81
  • 126
  • 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
  • 20,879
  • 9
  • 40
  • 61
0
sum([row.strip().split('\t') for row in rows],[])

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

NightShadeQueen
  • 3,284
  • 3
  • 24
  • 37