从字典追加时将元组列表转换为列表列表列表

2024-04-27 02:23:11 发布

您现在位置:Python中文网/ 问答频道 /正文

试图在python中合并混乱结构中的数据。你知道吗

首先,我得到一个元组列表

f = [('str1',7.0), ('str2',2.8), ('str3',11.2)]

还有一本字典

d = {'aa':'str2', 'bb':'str3', 'cc':'str1'}

其中每个值都是唯一的(无需检查),并且d中的每个值都与f的每个元组中的第一个元素一一对应。我需要将f更改为列表列表,并将d中的匹配键附加到f中列表的相应元素。在上面的示例中,所需的输出是

output = [['str1',7.0,'cc'], ['str2',2.8,'aa'], ['str3',11.2,'bb']]

现在我用嵌套for循环来做这个。最好的/“python-y”方法是什么?你知道吗


Tags: 数据元素示例列表foroutput字典结构
2条回答

您可以交换d中的键值对以获得更有效的解决方案:

f = [('str1',7.0), ('str2',2.8), ('str3',11.2)]
d = {'aa':'str2', 'bb':'str3', 'cc':'str1'}
new_d = {b:a for a, b in d.items()}
new_f = [[a, b, new_d[a]] for a, b in f]

输出:

[['str1', 7.0, 'cc'], ['str2', 2.8, 'aa'], ['str3', 11.2, 'bb']]

不需要交换,它可以直接用一种更为通俗的理解方式写出来:

output = [[dv, f2, dk] for f1, f2 in f for dk, dv in d.items() if dv == f1]

用简单的英语:创建一个由dv, f2, dk列表组成的列表,其中f2f中元组(f1, f2)的第二个值,其中dkdv是来自d的项dk: dv的键和值,只要dv的值与f1的值匹配。你知道吗

或者作为一个功能完整的脚本:

f = [('str1', 7.0), ('str2', 2.8), ('str3', 11.2)]

d = {'aa': 'str2', 'bb': 'str3', 'cc': 'str1'}

desired_output = [['str1', 7.0, 'cc'], ['str2', 2.8, 'aa'], ['str3', 11.2, 'bb']]

output = [[dv, f2, dk] for f1, f2 in f for dk, dv in d.items() if dv == f1]

print(output == desired_output)

相关问题 更多 >