Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

python - Can I add a variable name to itertools list?

This will print all of the possible combinations:

import itertools
iterables = [[0,1,2], ["3","46","5"]]
for item in itertools.product(*iterables, repeat=1):
    print(item)

like:

0,3
0,46
0,5
1,3
etc.

Suppose "A" has the values [0,1,2] and "B" has ["3", "46", "5], can I modify the code that the print will be something like:

A 0
B 3
A 0
B 46
A 1
B 3

etc.?

or any other way where the variable name is also part of the results?

Many thanks.

question from:https://stackoverflow.com/questions/66065213/can-i-add-a-variable-name-to-itertools-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Flatten the list of tuples, and zip it with the repeating sequence of explicit variable names.

from itertools import chain, cycle, product

for var, value in zip(cycle(["A", "B"]),
                      chain.from_iterable(product(*iterables))):
    print(var, value)

chain.from_iterable turns something like (x, y), (x, y) into x, y, x, y. cycle([x,y]) produces x, y, x, y, .... The cycle is infinite, but zip only consumes as much as needed to exhaust the flattened product sequence.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...