简体   繁体   中英

How to read multiple lists from STDIN in python?

I am newbie to python and trying to understand itertools.product. I am unable to read multiple lists from input.

Initially I have given manual input like below.

list1 = [1,2]
list2 = [3,4]
print(*product(list1, list2))

and got output as (1, 3) (1, 4) (2, 3) (2, 4) , which is perfectly fine.

I wanted the same thing for multiple lists to be used in product function.

I have tried like below

TotList = product(list(map(int,input().split())) for _ in range(2)) #in range function 2 can be vary
for item in TotList:
    print(*item)

But it is not working like a product tool

Current input:

1 2
3 4

Output:

[1, 2]
[3, 4]

Expected output:

(1, 3) (1, 4) (2, 3) (2, 4)

You have to specify * operator to unpack the iterables produced by map and feed it to product

>>> TotList = product(*(map(int,input().split()) for _ in range(2)))
1 2
3 4
>>> for item in TotList:
...     print(*item)
... 
1 3
1 4
2 3
2 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