首页 > 解决方案 > 如何从两个列表中获取字典可能性的每个排列?

问题描述

我有多组两个列表,我需要通过查看数据帧中跨行的每个排列将其转换为一个字典。

例如,如果有一个 ['cat1','cat2'] 列表和一个 ['top1','top2'] 列表,我想要一个结果字典 {'cat1':'top1',' cat1':'top2','cat2':'top1','cat2':'top2'}

这是我当前的代码,它接近但最终使用每个字母而不是字符串......

import pandas as pd

test_df = pd.DataFrame()
test_df['category'] = [['cat1'],['cat2'],['cat3','cat3.5'],['cat5']]
test_df['topic'] = [['top1'],[''],['top2','top3'],['top4']]


final_dict = {}
res = {}

for index, row in test_df.iterrows():
    print(row["category"], row["topic"])
    temp_keys = row["category"]
    temp_values = row["topic"]
    res = {}
    for test_key in temp_keys:
        #print(test_key)
        for test_value in temp_values:
            #print(test_value)
            #print(res)
            test_key = str(test_key)
            print(test_key)
            test_value = str(test_value)
            print(test_value)
            #res[key] = key
            #res = dict(zip(str(key),str(test_value)))
            res = dict(zip(str(test_key),str(test_value)))
            print(res)
            print('\n')

标签: pythonlistdictionarypermutation

解决方案


如果你想要一个元组列表而不是字典,你可以使用pd.MultiIndex.from_product

out = test_df.apply(pd.MultiIndex.from_product, axis=1).apply(list)
>>> out
0                                       [(cat1, top1)]
1                                           [(cat2, )]
2    [(cat3, top2), (cat3, top3), (cat3.5, top2), (...
3                                       [(cat5, top4)]
dtype: object

>>> out.tolist()
[[('cat1', 'top1')],
 [('cat2', '')],
 [('cat3', 'top2'), ('cat3', 'top3'), ('cat3.5', 'top2'), ('cat3.5', 'top3')],
 [('cat5', 'top4')]]

推荐阅读