简体   繁体   中英

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. 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:

numbers[i] *= M

To multiply every N -th element except the first one, we can construct a range:

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)

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 ; better use i as in your first loop
  • your are appending to the list, instead of overwriting the numbers with numbers[i] = numbers[i] * M or just 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
  • also, I don't see why you assign the entire numbers list (instead of eg just numbers[i] to total and print it...

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. What is N anyways?

With 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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