鉴于list
:
links = [ 'link1', 'link2', 'link3', 'link3', 'link4', 'link5', 'link6', 'link6', 'link7', 'link8', 'link9', 'link10']
此dicts
列表:
sources = [{'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}, {'src': ''}]
我想将每个src
值设置为其对应的链接,如下所示:
{'src': 'link1'}, {'src': 'link2'}
...
我试过了:
for s in sources:
for l in links:
s['src'] = l
print (s)
但这可以完成10次,而且我只想完成一次。
如何使用单线程实现这一目标?
答案 0 :(得分:4)
我认为src
中有其他内容,否则sources
没有意义:
for src, link in zip(sources, links):
src['src'] = link
可以将其写成一行:
[s.update({'src': x }) for s, x in zip(sources, links)]
但这可能是所谓的“副作用的理解”,并被大多数蟒蛇认为是不好的味道。一个循环更加pythonic。
以上也假设len(sources)==len(links)
另有考虑:
for src, link in zip(sources, itertools.cycle(links)):
src['src'] = link
将以循环方式填充链接。
如果这些src
dicts实际上是空的,则无需保留它们的列表,只需从头开始创建它:
sources = [{'src': x} for x in links]
答案 1 :(得分:2)
我不会在这里建议一个单行。只需一个简单的for循环就可以了:
>>> for d,link in zip(sources, links):
... d['src'] = link
>>> print(sources)
[{'src': 'link1'}, {'src': 'link2'}, {'src': 'link3'}, {'src': 'link3'}, {'src': 'link4'}, {'src': 'link5'}, {'src': 'link6'}, {'src': 'link6'}, {'src': 'link7'}, {'src': 'link8'}]
答案 2 :(得分:2)
links = [ 'link1', 'link2', 'link3', 'link3', 'link4', 'link5', 'link6', 'link6', 'link7', 'link8', 'link9', 'link10']
sources = [dict(src = ln) for ln in links]
print sources
[{'src': 'link1'}, {'src': 'link2'}, {'src': 'link3'}, {'src': 'link3'}, {'src': 'link4'}, {'src': 'link5'}, {'src': 'link6'}, {'src': 'link6'}, {'src': 'link7'}, {'src': 'link8'}, {'src': 'link9'}, {'src': 'link10'}]
print map(lambda v: dict(src = v), links)
或
# for python 3
print (list(map(lambda v: dict(src = v), links)))
[{'src': 'link1'}, {'src': 'link2'}, {'src': 'link3'}, {'src': 'link3'}, {'src': 'link4'}, {'src': 'link5'}, {'src': 'link6'}, {'src': 'link6'}, {'src': 'link7'}, {'src': 'link8'}, {'src': 'link9'}, {'src': 'link10'}]