Skip to main content
 首页 » 编程设计

python之列出对不同长度元素的理解

2025年05月04日14soundcode

我列表中的一些元素有点长,需要不同的处理方式。该列表如下所示:

a = [['red', 'square', 'up'], ['red', 'circle'],  
     ['blue', 'triangle'], ['blue', 'square'],  
     ['blue', 'octagon'], ['blue', 'diamond', 'down']] 

我几乎可以让它做我想做的事:

[[x[0], x[1] + 's'] for x in a] 

给出

[['red', 'squares'], 
 ['red', 'circles'], 
 ['blue', 'triangles'], 
 ['blue', 'squares'], 
 ['blue', 'octagons'], 
 ['blue', 'diamonds']] 

但这会丢失来自较长元素的信息。期望的输出是:

[['red', 'squares', 'up1'], ['red', 'circles'],  
['blue', 'triangles'], ['blue', 'squares'],  
 ['blue', 'octagons'], ['blue', 'diamonds', 'down1']] 

只是这样做

[[x[0], x[1] + 's', x[2] + '1'] for x in a] 

...不出所料会导致错误:

IndexError: list index out of range 

有什么办法吗?

请您参考如下方法:

您可以使用函数zip():

a = [['red', 'square', 'up'], 
     ['red', 'circle'], 
     ['blue', 'triangle'], 
     ['blue', 'square'], 
     ['blue', 'octagon'], 
     ['blue', 'diamond', 'down']] 
 
endings = ['', 's', '1'] 
 
[[i + j for i, j in zip(i, endings)] for i in a] 

结果:

[['red', 'squares', 'up1'], 
 ['red', 'circles'], 
 ['blue', 'triangles'], 
 ['blue', 'squares'], 
 ['blue', 'octagons'], 
 ['blue', 'diamonds', 'down1']]