Python:如何将itertools.product的元组结果转为拼接字符串列表
itertools.product Tuples into Concatenated Strings? I get exactly what you're aiming for—you want to turn each tuple output from itertools.product into a single combined string, instead of flattening all characters into one long, ungrouped list. Here are two straightforward, efficient solutions:
Solution 1: List Comprehension with str.join()
The most intuitive approach is to loop through each tuple from the product result and use ''.join() to concatenate its elements into a single string:
import itertools t1 = set(['R']) t2 = set(['Y']) t3 = set(['A', 'C', 'H', 'M', 'T', 'W', 'Y']) # Generate the product tuples product_tuples = list(itertools.product(t1, t2, t3)) # Convert each tuple to a concatenated string result = [''.join(item) for item in product_tuples] print(result) # Output: ['RYA', 'RYC', 'RYH', 'RYM', 'RYT', 'RYW', 'RYY']
Solution 2: Concise map() Approach
If you prefer a more compact style, you can use map() to apply ''.join directly to the iterator returned by itertools.product (this avoids converting the product to a list first, which saves memory for larger datasets):
import itertools t1 = set(['R']) t2 = set(['Y']) t3 = set(['A', 'C', 'H', 'M', 'T', 'W', 'Y']) result = list(map(''.join, itertools.product(t1, t2, t3))) print(result) # Output: ['RYA', 'RYC', 'RYH', 'RYM', 'RYT', 'RYW', 'RYY']
Why Your Initial "Flattening" Failed
When you tried flattening, you likely used a nested comprehension like [char for item in product_tuples for char in item]—this pulls every character out of every tuple and merges them into one flat list. Instead, we need to process each tuple as a single unit and join its elements together, not break them apart.
内容的提问来源于stack exchange,提问作者dk09

