You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何将itertools.product的元组结果转为拼接字符串列表

How to Convert 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:56:35