简体   繁体   中英

Modify list of sets containing sets in Python3

I am trying to create a list with tuples as elements. Each tuple has 4 integers. The 2 first integers are a result of zipping 2 ranges , while the other 2 from 2 different ones.

I am using this code to create the tuples and the final list, which is derived from the cartesian product, as seen here: Get the cartesian product of a series of lists?

import itertools
first_range = list(zip((10**exp for exp in range(0,7)),(10**exp for exp in range(1,8))))
second_range = list(zip((5*10**exp if exp != 1 else 10**2 for exp in range(1,8)),(5*10**exp for exp in range(2,9))))
final_list = list(itertools.product(first_range,second_range))

The issue with this code is that the final results looks like this:

[((1, 10), (100, 500)), ((1, 10), (500, 5000)), ((1, 10), (5000, 50000)), ((1, 10), (50000, 500000)), ((1, 10), (500000, 5000000)), ((1, 10), (5000000, 50000000)), ...

Where each list element is a tuple containing 2 other tuples, while what I want is this:

[(1, 10, 100, 500), (1, 10, 500, 5000), (1, 10, 5000, 50000), (1, 10, 50000, 500000), (1, 10, 500000, 5000000), (1, 10, 5000000, 50000000), ...

ie each list element is a tuple containing 4 integers.

Any ideas would be appreciated. Must be working on python3. EDIT: Updated the non-working parts of the code thanks to ShadowRanger's comments

So, I was certain I was close to the answer once I posted this question, but I did not realize I was this close. The way to fix the issue with the extra tuples is:

import itertools
first_range = zip((10**exp for exp in range(7)),(10**exp for exp in range(1,8)))
second_range = zip((5*10**exp if exp != 1 else 10**2 for exp in range(1,8)),(5*10**exp for exp in range(2,9)))
iterator_of_tuples = itertools.product(first_range,second_range)

# the next line solves my issue
final_list = [x + y for x, y in iterator_of_tuples]

What I did was a simple merging of tuples: How to merge two tuples in Python? . Not sure why I didnt think of it earlier

Edit: Updated the answer based on ShadowRanger's input

Your expected output is not the cartesian product of the two ranges.

If you want your expected output something like this will work:

final_list = [(*x, *y) for x, y in zip(first_range, second_range)]

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