[英]How to match items in two different lists and create a new list based on the matches in python?
I have a list in python called "multiple_ids" with a bunch of ids and I have another list called "ids_singular" as well as another list called "alias".我在 python 中有一个名为“multiple_ids”的列表,其中包含一堆 id,我还有另一个名为“ids_singular”的列表以及另一个名为“alias”的列表。
"ids_singular" and "alias" are both the same size and the index of "ids_singular" corresponds to the index of "alias". “ids_singular”和“alias”的大小相同,“ids_singular”的索引对应“alias”的索引。 What this means is that say the third value in the "alias" list is another way to represent the third value in "ids_singular".
这意味着说“别名”列表中的第三个值是表示“ids_singular”中第三个值的另一种方式。
The list "miltiple_ids" is larger than the other two lists and includes all values in "ids_singular', but there are duplicates as well. Every id in "mutiple_ids" can be found in "ids_singular".列表“miltiple_ids”比其他两个列表大,包括“ids_singular”中的所有值,但也有重复。“mutiple_ids”中的每个id都可以在“ids_singular”中找到。
What I am looking to do is for code that will replace each item (id) in "multiple_ids" with the matching alias from the "alias" list based on the "ids_singular" list.我要做的是使用基于“ids_singular”列表的“别名”列表中的匹配别名替换“multiple_ids”中的每个项目(id)的代码。
I have tried a double for loop where I first iterate through all the "multiple_ids", then iterate through all the "ids_singular" and if they are a match, create a new list that has the alias for the id based on the same index of "alias" list.我尝试了一个双循环,我首先遍历所有“multiple_ids”,然后遍历所有“ids_singular”,如果它们匹配,则创建一个新列表,该列表具有基于相同索引的 id 别名“别名”列表。
for i in (multiple_ids):
for j in range(len(ids_singular)):
if i==ids_singular[j]:
new_multiple_ids.append(alias[j])
print(new_multiple_ids)
When I run this code, nothing happens当我运行此代码时,没有任何反应
I believe this is what you want:我相信这就是你想要的:
multiple_ids = ['abc', 'def', 'xyz', 'def', 'xyz']
ids_singular = ['abc','def','xyz']
alias = ['a_abc','a_def', 'a_xyz']
d = dict(zip(ids_singular, alias))
result = [d[item] for item in multiple_ids]
print(result) $ -> ['a_abc', 'a_def', 'a_xyz', 'a_def', 'a_xyz']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.