Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字典追加时将元组列表转换为列表列表_Python - Fatal编程技术网

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

Python 从字典追加时将元组列表转换为列表列表,python,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'

试图在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”这样做的更好方法是什么?

您可以在
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
列表组成的列表,其中
f2
f
中元组
(f1,f2)
的第二个值,其中
dk
dv
d
中项目的键和值,每当
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)