这是python代码,我正在做2小时的睡眠,请帮我解决这个问题,因为代码的问题是编写一个程序,在偶数索引处将列表中的所有元素相乘。
def EvenProduct(arr, n):
even = 1
for i in range (0,n):
if (i % 2 == 0):
even *= arr[i]
print("Even Index Product : " , even)
# Driver Code
arr = int(input("Enter the size of the list "))
print("\n")
num_list = list(int(num) for num in input("Enter the list items separated by space ").strip().split())[:arr]
print("User list: ", num_list)
n = len(arr)
EvenProduct(arr, n)我得到了这个错误
Traceback (most recent call last):
File "<string>", line 26, in <module>
TypeError: object of type 'int' has no len()发布于 2022-09-16 16:26:05
你想写n = len(num_list)。
值arr是一个整数,因此,正如错误指示的那样,它没有长度。
不需要将长度传递给函数,您可以使用len(arr)在里面计算它。
您可以使用枚举全局函数同时获得索引和值。
#!/usr/bin/env python
def evens_product(l):
product = 1
for i,v in enumerate(l):
if i % 2 == 0:
product *= v
return product
result = evens_product([1,2,3,4,5,6])
print(result) # 15https://stackoverflow.com/questions/73747696
复制相似问题