简体   繁体   中英

extract list pattern from list of list in python

I have a list of the form -

a_list = [[1, [2, 3, 4]], [2, [3, 4]], [3, [4]]]

I want to convert it to the form -

b_list = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]

Using the list comprehension, I have tried with below code

for lst in tup:
    for lst1 in tup[1]:
        tup2 = [lst[0],lst1]

and getting (which is wrong)-

tup2 = [3, [3, 4]]

Please help, Thanks in advance

Simple to do with a list comprehension:

a_list = [[1, [2, 3, 4]], [2, [3, 4]], [3, [4]]]

b_list = [[x,y] for [x,b] in a_list for y in b]

print(b_list)

result:

[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

using [x,b] unpacks the items into x as number and b as your list. Loop through elements of b and build the couples, flat-style.

You could try something like this , no matter how many int are there :

for sub_list in b:
    for items in sub_list:
        if isinstance(items, list):
            track = sub_list.index(items)
            first = sub_list[:track]
            second = sub_list[track:][0]
            import itertools

            print([list(k) for k in itertools.product(first, second)])

test case:

b = [[1, [2, 3, 4]], [2, [3, 4]], [3, [4]]]

output:

[[1, 2], [1, 3], [1, 4]]
[[2, 3], [2, 4]]
[[3, 4]]

test case 2:

b=[[1,2,[2, 3, 4]], [2,3,5,6 ,[3, 4]], [3, [4]]]

output:

[[1, 2], [1, 3], [1, 4], [2, 2], [2, 3], [2, 4]]
[[2, 3], [2, 4], [3, 3], [3, 4], [5, 3], [5, 4], [6, 3], [6, 4]]
[[3, 4]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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