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

如何用Python从字符串列表创建嵌套字典?

从字符串列表构建索引对应字符集合的字典

给定字符串列表:

str_list = ['game', 'club', 'party', 'play']

要生成的目标字典中,键是字符的位置索引,对应值是所有字符串在该位置上的字符集合(或列表,取决于是否保留重复字符)。

简洁实现:字典推导式

如果需要自动去重的集合(集合会剔除重复字符):

str_list = ['game', 'club', 'party', 'play']
result = {
    idx: {s[idx] for s in str_list if idx < len(s)}
    for idx in range(max(len(s) for s in str_list))
}
print(result)

如果需要保留重复字符(用列表存储):

str_list = ['game', 'club', 'party', 'play']
result = {
    idx: [s[idx] for s in str_list if idx < len(s)]
    for idx in range(max(len(s) for s in str_list))
}
print(result)

基于嵌套循环的实现(贴近你的初始思路)

核心是遍历字符位置索引,而非列表元素的索引:

str_list = ['game', 'club', 'party', 'play']
res = {}

# 先确定所有字符串的最大长度,覆盖所有可能的索引
max_length = max(len(s) for s in str_list)

for idx in range(max_length):
    # 初始化当前索引对应的集合
    res[idx] = set()
    for s in str_list:
        # 避免索引越界,只处理长度足够的字符串
        if idx < len(s):
            res[idx].add(s[idx])

print(res)

如果要保留重复字符,把集合换成列表即可:

str_list = ['game', 'club', 'party', 'play']
res = {}

max_length = max(len(s) for s in str_list)

for idx in range(max_length):
    res[idx] = []
    for s in str_list:
        if idx < len(s):
            res[idx].append(s[idx])

print(res)

你的初始思路问题说明

你原来的循环逻辑是遍历列表的元素索引,再遍历每个字符串的字符,但没有关联到字符的位置索引,因此无法正确将字符映射到对应的字典键。调整循环的遍历对象为字符位置索引,就能解决这个问题。

内容的提问来源于stack exchange,提问作者L10B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:10:48