嵌套for循环的列表理解

2024-06-01 01:16:42 发布

您现在位置:Python中文网/ 问答频道 /正文

无法将以下嵌套for循环转换为列表:

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

输入数据以制表符分隔:

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

期望输出:

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

Tags: inforelementselementoldrowolcole
2条回答

像这样

with open('tabdelim.txt') as rows:
    lstcmp = [item for row in rows for item in row.strip().split('\t')]
    print('\n'.join(lstcmp))
sum([row.strip().split('\t') for row in rows],[])

内置的sum对于平展列表非常有用。你知道吗

相关问题 更多 >