[英]Iterating through dictionary values to form URL
I'm trying to iterate through the values in the dictionary below in order to add each value to form a unique URL (using Python 2 here):我正在尝试遍历下面字典中的值,以便添加每个值以形成唯一的 URL(此处使用 Python 2):
base_url = 'https://www.edimark.fr/resultat-recherche/magazine/'
magazine = {
'La Lettre du Cancerologue': '14',
'La Lettre du Pharmacologue': '10',
"La Lettre de l'Hepato gastroenterologue": '4',
"La Lettre de l'Infectiologue": '2'
}
When I iterate through itervalues, it sequentially adds each number to the previous number.当我遍历 itervalues 时,它会按顺序将每个数字添加到前一个数字。 Code and output below:
代码和输出如下:
for itervalue in magazine.itervalues:
base_url = base_url + itervalue
print base_url
https://www.edimark.fr/resultat-recherche/magazine/4
https://www.edimark.fr/resultat-recherche/magazine/410
https://www.edimark.fr/resultat-recherche/magazine/4102
https://www.edimark.fr/resultat-recherche/magazine/410214
Whereas the intended output is achieved when I do not save the result to a variable...而当我不将结果保存到变量时就实现了预期的输出......
for itervalue in magazine.itervalues:
base_url + itervalue
'https://www.edimark.fr/resultat-recherche/magazine/4'
'https://www.edimark.fr/resultat-recherche/magazine/10'
'https://www.edimark.fr/resultat-recherche/magazine/2'
'https://www.edimark.fr/resultat-recherche/magazine/14'
Could anyone please let me know what I'm doing wrong here?谁能让我知道我在这里做错了什么? Pretty new to Python, so any help is much appreciated!
Python 的新手,所以非常感谢任何帮助!
you could use:你可以使用:
for itervalue in magazine.itervalues:
aux_base_url = aux_base_url + itervalue
print aux_base_url
you are changing the value for base_url
on each iteration adding to the original base_url
all the values from magazine.itervalues
, to fix this you could store the intermediary result in an auxiliary variable aux_base_url
您为不断变化的价值
base_url
在每次迭代添加到原base_url
一切从值magazine.itervalues
,要解决这个问题,你可以在中间结果存储在一个辅助变量aux_base_url
the auxiliary variable makes sense if you want to do more then just to print if you want only to print is more convenient to use:辅助变量是有意义的,如果你想做更多然后只是打印,如果你只想打印更方便使用:
print base_url + itervalue
base_url = base_url + itervalue
This is cumulative.这是累积的。 You have to assign the new URL to another variable, for example:
您必须将新 URL 分配给另一个变量,例如:
url = base_url + itervalue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.