Skip to main content
 首页 » 编程设计

python之将列表中的每个第 N 个元素乘以 M

2025年05月04日14shanyou

我有一个我似乎无法弄清楚的问题。我是 Python 的新手,编码才三个星期。感谢您的帮助。

问题:

我们传入 3 个输入:

  • 数字列表
  • 乘数,M
  • 一个值,N

You should multiply every Nth element (do not multiply the 0th element) by M. So if N is 3, you start with the 3rd element, which is index 2.

If there are less than N elements then you should output the unchanged input list.

我似乎无法弄清楚这一点。我在这里尝试了很多不同的东西。目前,我有以下内容,但根本不起作用。

提供:

import sys 
M= int(sys.argv[2]) 
N= int(sys.argv[3]) 
 
numbers= sys.argv[1].split(',') 
for i in range(0, len(numbers)): 
  numbers[i]= int(numbers[i]) 

我的代码:

for N in numbers: 
    if numbers[i] > 0: 
    total = N * M 
    print(total) 
else: 
    print(numbers) 

输出:

我什至不接近输出应该是什么。对此感到迷茫。这是我的代码的结果。看起来他们想要列表中的输出。

Program Failed for Input: 1,2,3,4,5,6 5 3 
Expected Output: [1, 2, 15, 4, 5, 30] 
Your Program Output: 
5 
10 
15 
20 
25 
30 

请您参考如下方法:

您可以尝试使用切片进行列表推导。

numbers[N-1::N] = [x * M for x in numbers[N-1::N]]