简体   繁体   中英

Getting 3D list rather than 2D list

My goal is to produce a list comprising all combination of elements from specified groups. The output should be a 2D list but I am unable to generate anything other than a 3D list. Can I generate the 2D list directly, or is it necessary to convert the 3D list to a 2D list? If so, how?

# elements comprising each of groups a1-a4
a1 = ['one','two','three']
a2 = ['four','five','six']
a3 = ['seven','eight','nine']
a4 = ['ten','eleven','twelve']

# each row in b specifies two or more groups, whereby all combinations of one
# element from each group is found
b  = [[a1,a2],
      [a3, a4]]

# map(list,...) converts tuples from itertools.product(*search) to lists
# list(map(list,...)) converts map object into list
# [...] performs list comprehension
l = [list(map(list, itertools.product(*search))) for search in b]
print(l)

Output: [[['one', 'four'], ..., ['nine', 'twelve']]]

Desired Output: [['one', 'four'], ..., ['nine', 'twelve']]

Obviously, you can create your list as follows:

l = []
for search in b:
    l += list(map(list, itertools.product(*search)))

But if you want to stick with a list comprehension, you can do:

l = list(itertools.chain(*[map(list, itertools.product(*search)) for search in b]))

Or:

l = list(map(list, itertools.chain(*[itertools.product(*search) for search in b])))

It creates and chains the two cartesian products, and then maps the tuples to lists.

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