我有一个如下所示的列表:
working_list=['one', 'two', 'three', 'four', 'five']
我想要一个如下所示的新列表:
output_list=['one or two','one or two','three','four or five','four or five']
为此,我创建了另外两个列表:
old_names=[['one','two'],['four','five']]
new_names=['one or two','four or five']
然后我尝试了:
output_list=[]
for item in working_list:
for a_list in old_names:
if item in a_list:
index=old_names.index(a_list)
new_name=new_names[index]
output_list.append(new_name)
else:
output_list.append(item)
print(output_list)
但这给了我一个输出:
['one or two', 'one', 'one or two', 'two', 'three', 'three', 'four', 'four or five', 'five', 'four or five']
关于如何解决这个问题有什么想法吗?
非常感谢!
最佳答案
对于任何类型的 a->b 映射,您应该使用字典。例如,将 old_names
和 new_names
列表替换为 old_to_new_names
字典
working_list = ['one', 'two', 'three', 'four', 'five']
old_to_new_names = {
"one": "one or two",
"two": "one or two",
"four": "four or five",
"five": "four or five",
}
output_list = [old_to_new_names.get(i, i) for i in working_list]
old_to_new_names.get
方法在字典中查找 i
,如果不存在则返回 i
(第二个参数是默认)
关于python - 基于另外两个列表在 Python 中创建列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67919611/