简体   繁体   English

变量列表项的长度

[英]Variable list item's length

I have a list which each of its elements could have a different number of elements. 我有一个列表,其中每个元素可以具有不同数量的元素。 In lst1, each list item has 3 items while in lst2, each list item has 2 items. 在lst1中,每个列表项有3个项目,而在lst2中,每个列表项有2个项目。

lst1=[([{'s1'}, 30], [{'s2'}, 28], [{'s3'}, 28]), ([{'s1'}, 30], [{'s2'}, 28], [{'s4'}, 30])]

lst2=[([{'s1'}, 30], [{'s2'}, 28]), ([{'s1'}, 30], [{'s4'}, 22])]

Generally, The number of list elements is not fixed and each item of the list would contain 1,2,3,4,5 or 6 items inside of itself(in lst1, each list item contains 3 items). 通常,列表元素的数量不是固定的,并且列表的每个项自身内部将包含1,2、3、4、5或6个项(在lst1中,每个列表项包含3个项)。 The output that should be generated given ls1 is as follows: 给定ls1时应生成的输出如下:

[{'s1','s2','s3'},{'s1','s2','s4'}]

While the following outcome is expected for lst2: 虽然预期lst2具有以下结果:

[{'s1','s2'},{'s1','s4'}] 

Following code works JUST for the lst2: 以下代码仅适用于lst2:

[x[0][0]|x[1][0] for x in lst2]

Actually, the problem is converting this part of code 'x[0][0]|x[1][0]' to a dynamic one. 实际上,问题是将这部分代码“ x [0] [0] | x [1] [0]”转换为动态代码。 If each item of the list has 2 subitems, 'x[0][0]|x[1][0]' works fine. 如果列表的每个项目都有2个子项目,则'x [0] [0] | x [1] [0]'可以正常工作。 While, If each item of the list has 3 subitems, we should have ''x[0][0]|x[1][0]|x[2][0]' and so far so forth. 同时,如果列表中的每个项目都有3个子项目,则我们应具有“ x [0] [0] | x [1] [0] | x [2] [0]”,等等。

I know how to generate the output using multiple for loops. 我知道如何使用多个for循环生成输出。 But, I appreciate if anyone has a better idea for implementation of the above code, either through an inline loop or other faster ways. 但是,如果有人通过内联循环或其他更快的方法来实现上述代码,我将不胜感激。

You should use a general set union operation instead of the binary union operator. 您应该使用通用集合并集运算符而不是二进制并集运算符。

[set.union(*[x[0] for x in item]) for item in lst1]
#[{'s1', 's2', 's3'}, {'s1', 's2', 's4'}]
[set.union(*[x[0] for x in item]) for item in lst2]
#[{'s1', 's2'}, {'s1', 's4'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM