我对编码很陌生,我正在做一项作业,我必须在一个巨大的列表中找到所有偶数索引整数的乘积:
number_list = [12, 41, 10, 34, 37, 2, 3, 8, 42, 46, 46, 27, 13, 49, 41, 2, 28, 21, 37, 27, 31, 19, 46, 7, 50, 1, 46, 45, 19, 10, 14, 8, 44, 14, 10, 4, 23, 29, 46, 18, 32, 40, 32, 7, 33, 45, 26, 24, 43, 45]
该问题建议使用 range(len(list)),它为我提供范围 (1,50),但我不知道这有什么相关性。我设法在不使用该方法的情况下得到了答案:
number_list = [12, 41, 10, 34, 37, 2, 3, 8, 42, 46, 46, 27, 13, 49, 41, 2, 28, 21, 37, 27, 31, 19, 46, 7, 50, 1, 46, 45, 19, 10, 14, 8, 44, 14, 10, 4, 23, 29, 46, 18, 32, 40, 32, 7, 33, 45, 26, 24, 43, 45]
result = 1
evenlist = number_list[::2]
for num in evenlist:
result = result * num
range(len(list)) 在这里有什么用?
最佳答案
可能是这样的,您使用数组的索引引用它;
number_list = [12, 41, 10, 34, 37, 2, 3, 8, 42, 46, 46, 27, 13, 49, 41, 2, 28, 21, 37, 27, 31, 19, 46, 7, 50, 1, 46, 45, 19, 10, 14, 8, 44, 14, 10, 4, 23, 29, 46, 18, 32, 40, 32, 7, 33, 45, 26, 24, 43, 45]
result = 1
for idx in range(0, len(number_list), 2):
result = result * number_list[idx]
关于python - 如何使用 range(len(list)) 查找列表中所有偶数索引整数的乘积?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53834423/