python:将列表中的项替换为另一个列表中的项
我有一本字典:python:将列表中的项替换为另一个列表中的项,python,list,dictionary,Python,List,Dictionary,我有一本字典: d = {'name': ['sarah', 'emily', 'brett'], 'location': ['LA', 'NY', 'Texas']} 我还有一份清单: l = ['name', 'location'] 我想用字典d中的列表['sarah','emily','brett']替换列表l中的'name'(位置也是一样) 因此,结果将是: l = ['sarah', 'emily', 'brett', 'LA', 'NY', 'Texas'] for item
d = {'name': ['sarah', 'emily', 'brett'], 'location': ['LA', 'NY', 'Texas']}
我还有一份清单:
l = ['name', 'location']
我想用字典d
中的列表['sarah','emily','brett']
替换列表l
中的'name'(位置也是一样)
因此,结果将是:
l = ['sarah', 'emily', 'brett', 'LA', 'NY', 'Texas']
for item in l:
l.append(d[item])
l.remove(item)
这就是我所做的,我得到了一个类型错误,不可损坏的类型:“list”。
我应该怎么做才能解决这个问题?如果您在循环中迭代列表中的项目,则不应该更改循环中的列表 尝试创建一个新的,然后重命名它。垃圾收集器将处理旧版本的
l
new_l = []
for item in l:
new_l.extend(d[item])
l = new_l
最简单的解决方案是创建一个新列表:
l = [y for x in l for y in d[x]]
结果为以下替代项:
print l
>>> ['sarah', 'emily', 'brett', 'LA', 'NY', 'Texas']
使用此代码:
l = [d.get(k, k) for k in l]
在循环时不要更改列表,因为迭代器不会被通知您的更改 要替换它们,只需生成一个新列表,其中包含用
l
项选择的d
列表
[d[item] for item in l]
如果您不确定l
中的所有项目都是d
中的键,则可以在尝试从d
获取之前添加测试:
[d[item] for item in l if d.has_key(item)]
将.append()替换为.extend()
在我的例子中,列表中的项目仅部分显示在字典中。为了避免错误,我使用了:
[y代表l中的x代表d中的y.get(x,[x])]
当测试数据发生如下变化时:
l = ['name', 'location', 'test']
结果如下:
print([y for x in l for y in d.get(x,[x])])
>>> ['sarah', 'emily', 'brett', 'LA', 'NY', 'Texas', 'test']
提示:使用new_l.extend()
获取OP的预期输出。
print([y for x in l for y in d.get(x,[x])])
>>> ['sarah', 'emily', 'brett', 'LA', 'NY', 'Texas', 'test']