简体   繁体   English

在python中将数字相乘

[英]Multiplying numbers in a list in python

I need a loop to multiply part of a list. 我需要一个循环来乘法一部分列表。 I have multiply every Nth element (except 0th) by M. The list is called numbers, the multiplier is M, and the loop should start multiplying at the Nth number. 我将第N个元素(第0个元素除外)乘以M。该列表称为数字,乘数为M,循环应从第N个数字开始相乘。 This is what I have: 这就是我所拥有的:

for i in range(0, len(numbers)):
  numbers[i]= int(numbers[i])

for M in range (N, len(numbers)):
  if numbers[N] > 0:
    numbers.append[N]
  if numbers[N] < 0:
    total = numbers
    print (total)

It keeps returning the wrong output, I've tried everything I can think of to fix it but it still won't work. 它总是返回错误的输出,我已经尽力解决了所有问题,但仍然无法正常工作。

You usually multiply a number with the asterisk ( * ). 您通常将数字乘以星号( * )。 So we can multiply the i -th number with: 因此,我们可以将第i个数乘以:

numbers[i] *= M

To multiply every N -th element except the first one, we can construct a range: 要乘除第一个元素之外的每个第N个元素,我们可以构造一个范围:

for i in range(N, len(numbers), N):
    numbers[i] *= M

The last argument of the range is the step , it means that we thus each time increment i , until reach len(numbers) range的最后一个参数是step ,这意味着我们因此每次递增i ,直到达到len(numbers)

There a quite a few problems and oddities in your code: 您的代码中有很多问题和奇怪之处:

  • you use M as the loop variable, thus overwriting the multiplier stored in M ; 您将M用作循环变量,从而覆盖存储在M的乘数; better use i as in your first loop 最好在第一个循环中使用i
  • your are appending to the list, instead of overwriting the numbers with numbers[i] = numbers[i] * M or just numbers[i] *= M 您将附加到列表中,而不是用numbers[i] = numbers[i] * M或仅覆盖numbers[i] *= M覆盖数字
  • I don't see how the > 0 and < 0 checks relate to your question, but you should probably check numbers[i] instead of numbers[N] , the letter being always the same 我看不到> 0< 0检查与您的问题的关系如何,但您应该检查numbers[i]而不是numbers[N] ,字母始终相同
  • also, I don't see why you assign the entire numbers list (instead of eg just numbers[i] to total and print it... 另外,我不明白为什么要分配整个numbers列表(而不是仅将numbers[i]分配到total并打印出来...)

You could also use a list comprehension and assign back to a slice of the original list: 您还可以使用列表推导并分配回原始列表的一部分:

>>> N, M = 3, 10
>>> numbers = list(range(10))
>>> numbers[N::N] = [x*M for x in numbers[N::N]]
>>> numbers
[0, 1, 2, 30, 4, 5, 60, 7, 8, 90]
numbers = [int(n) for n in numbers]

this is for the first function. 这是第一个功能。 It's called a list comprehension The second one you got M and N mixed up i guess. 这被称为列表理解 。我猜你把MN混在一起的第二个。 What is N anyways? N到底是什么?

With map : map

map(lambda (i, el): el*M if i%N==0 else el, enumerate(numbers))

Skipping the first index: 跳过第一个索引:

map(lambda (i, el): el*M if i%N==0 and i>0 else el, enumerate(numbers))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM