简体   繁体   English

按索引和名称匹配三个列表

[英]Match three lists by index and name

Example of what I'm after: 我所追求的例子:

main_names = ['apple', 'orange', 'banana', 'pear', 'mango', 'peach', 'strawberry']
changing_names = ['apple', 'banana', 'cucumber', 'peach', 'pear', 'fish']
changing_values = [100,      200,       300,       400,    500,    600]


output_names = ['apple', 'NA', 'banana', 'pear', 'NA', 'peach', 'NA']
output_values = [100,    'NA',   200,      500,  'NA',   400,   'NA'

added_names = ['cucumber', 'fish']
added_values = [300, 600]

I am using a previous question of mine as reference, Match two lists by index and name , where I have learnt to successfully retrieve output/added_names. 我使用我的上一个问题作为参考, 通过索引和名称匹配两个列表 ,在这里我学会了如何成功检索输出/添加名称。

For some background, changing_names and changing_values are linked via their index (Which is where my troubles arise, I would use a dict but I'm not sure how I can manipulate a dict in the way I need) 对于某些背景,changing_names和changing_values通过它们的索引链接(这是我遇到麻烦的地方,我会使用dict,但不确定如何以所需的方式操作dict)

I don't know how I can shift the changing/added_values list to stay consistent with the index of the output_names list. 我不知道如何才能更改/ addtings_values列表以保持与output_names列表的索引一致。 If there's a way to work with multiple lists while avoiding linking them together via index, I'd be very happy to know. 如果有一种方法可以处理多个列表,同时又避免通过索引将它们链接在一起,我将非常高兴知道。

A dictionary and some list comprehensions are one way: 字典和一些列表理解是一种方法:

mapper = dict(zip(changing_names, changing_values))

output_names = [x if x in changing_names else 'NA' for x in main_names]
output_values = [mapper.get(x, 'NA') for x in output_names]

added_names = [x for x in changing_names if x not in main_names]
added_values = [mapper.get(x, 'NA') for x in added_names]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM