python - 如何从两个列表中获取字典可能性的每个排列?
问题描述
我有多组两个列表,我需要通过查看数据帧中跨行的每个排列将其转换为一个字典。
例如,如果有一个 ['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')
解决方案
如果你想要一个元组列表而不是字典,你可以使用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')]]
推荐阅读
- python - 使用 pyreder/pyglet/openGL 将 3d 顶点映射到像素
- grafana - 如何在 Grafana 7 中显示 HTML
- python - Leetcode 5 最长回文子串 (python)
- python - 如何在不使用脚本录制和回放选项的情况下自动化 SAP GUI 流程
- php - codeigniter 输入日期字段不应接受前几天
- javascript - Javascript高阶函数:
- next.js - 带有本地化的 Next.js - 使用入口配置在子路径上部署
- python - 有人可以解释这两个函数之间的时间复杂度吗?
- r - 连接 X 和 Y 轴
- reactjs - tsc compile in React (create-react-app) 需要明确的编译标志,尽管我在 tsconfig.json 中设置了它们