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)
I don't know how I can shift the changing/added_values list to stay consistent with the index of the output_names list. 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.