对长度可变的元素的列表理解

时间:2019-04-01 11:22:33

标签: python python-3.x list-comprehension

我列表中的某些元素较长,需要不同的处理。此列表如下所示:

   ~SkipList()
   {
        for (Node<T> *p, *c; p = head; )
        {
            head = head->above;
            do c = p, p = p->next, delete c; while (p);
        }
   }

我几乎可以做到这一点:

SSLCertificateFile "<path-to-file>"
SSLCertificateKeyFile "<path-to-file>"

给出

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']]

任何想法如何做到这一点?

4 个答案:

答案 0 :(得分:3)

您可以使用函数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']]

答案 1 :(得分:2)

您出错了,因为有时您的x2个元素,有时还有3。我修改了您的代码来处理此问题:

a = [['red', 'square', 'up'], ['red', 'circle'], 
     ['blue', 'triangle'], ['blue', 'square'], 
     ['blue', 'octagon'], ['blue', 'diamond', 'down']]
t = [[x[0], x[1] + 's'] if len(x) == 2 else [x[0], x[1] + 's', x[2] + '1'] for x in a]
print(t)

输出:

  

[[''红色','正方形','up1'],['红色','圆圈'],['蓝色','三角形'],['蓝色','正方形'],['蓝色”,“八边形”],['蓝色','钻石','down1']]

答案 2 :(得分:1)

获取len()中每个elem的{​​{1}},并进行相应的操作:

理解

list

输出

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

for elem in a:
    if len(elem) < 3:
        print([elem[0], elem[1] + "s"])
    else:
        print([elem[0], elem[1] + "s " + elem[2]+ "1"])

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

list-comprehension

答案 3 :(得分:0)

如果您只想检查嵌套列表是否具有len> 2,这对我有用:

[[x[0], x[1] + 's'] if len(x) == 2 else [x[0], x[1]+'s', x[2]+'1'] for x in a]

输出:

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