Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multiplex lists using zip
#11
If you look at product(values, suits) you get <itertools.product at 0xa2cfb71908>.
This is no list, this is an iterator.
If you do list(product(values, suits)) than the list() functions takes all tuples from product() one after another and creates the list of tuples.
So using the list comprehension [f'{v}{s}' for v,s in itertools.product(values, suits)] you get the desired list and time is O(n*m).
Please accept this. I won´t answer to any more complaints from you about this matter. Sorry.
Reply
#12
(Dec-02-2019, 06:24 PM)ichabod801 Wrote: No, it's all in the same pass. That's what ThomasL (quoting the documentation) was saying. Product creates the first tuple, and then passes that out to the list comprehension, which then creates the first string. Only then does product create the second tuple, and again that is returned/yielded and processed into a string before the third tuple is generated. So you are only passing through once, for O(n * m).

Ok, I got it. The iterable does not create the values, only yields them on demand.
Very good. Thank you.
Reply
#13
You can flatten the nested loop with itertools.product.
Instead of converting the values into a str you can use format-strings or
if you're not allowed to use Python 3.6, then with the format method of str.

The example is with format-string.
import itertools


values = list(range(2,11)) + ['J', 'Q', 'K', 'A']
suits = ['♠', '♦', '♥', '♣']
prod = itertools.product(values, suits)
print([f'{val}{suit}' for val, suit in prod])

Btw: You can use also inline addition to extend a list.

values = list(range(2,11))
values += ['J', 'Q', 'K', 'A']
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,312 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,187 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020