python - 基于另外两个列表在 Python 中创建列表?

标签 python nested-lists

我有一个如下所示的列表:

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_namesnew_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/

相关文章:

python - 列表列表更改意外地反射(reflect)在子列表中

Python:列表附加问题

python - 从列表列表中随机选择项目给出 ValueError

Javascript:将平面 json 结构解析并排序为嵌套数组?

python - 如何创建带有阈值线的 matplotlib 条形图?

python - 循环测试函数时如何让Pytest识别迭代次数

python - BS4 : removing <a> tags

python - 将一个元组复制到多个组中

python - 在没有环境变量的配置文件中设置 python 搜索路径(即 PYTHONPATH)

python - 如何使用另一个列表对多维列表进行排序