我试图遍历下面字典中的值,以添加每个值以形成唯一的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'
}
当我遍历itervalues时,它会依次将每个数字添加到先前的数字。代码和输出如下:
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
当我不将结果保存到变量中时,将实现预期的输出...
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'
有人可以让我知道我在做什么错吗?对Python来说还很陌生,因此非常感谢您的帮助!
答案 0 :(得分:0)
您可以使用:
int
您要在每次迭代中更改for itervalue in magazine.itervalues:
aux_base_url = aux_base_url + itervalue
print aux_base_url
的值,将base_url
中的所有值添加到原始base_url
中,要解决此问题,您可以将中间结果存储在辅助变量{中{1}}
如果您想做更多的事情,那么辅助变量才有意义,而如果您只想打印,则只需打印就更方便了:
magazine.itervalues
答案 1 :(得分:0)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Creating an array by user keyboard input
Scanner sc = new Scanner(System.in);
System.out.print("Length of array: ");
int n = sc.nextInt();
int[] numbers = new int[n];
System.out.printf("Type in %d integer elements of array: ", numbers.length);
int index = 0;
while (index < n && sc.hasNextInt()) {
numbers[index++] = sc.nextInt();
}
// created method for printing arrays
printArray(numbers);
}
static void printArray(int[] numbers) {
for (int n : numbers) {
System.out.print(n + " ");
}
}
}
这是累积的。您必须将新的URL分配给另一个变量,例如:
Length of array: 3
Type in 3 integer elements of array: 10 20 30
10 20 30