python-3.xlistsubitem

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=[([{'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). The output that should be generated given ls1 is as follows:

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

While the following outcome is expected for lst2:

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

Following code works JUST for the 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. If each item of the list has 2 subitems, 'x[0][0]|x[1][0]' works fine. 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.

I know how to generate the output using multiple for loops. But, I appreciate if anyone has a better idea for implementation of the above code, either through an inline loop or other faster ways.


Solution

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