How do I add odd value values ​​in python?

I need to process the list to add an amount to every odd position. For example, if I start with

def main():
    L = [1,3,5,7,9,11]

      

and need to add 5 to every odd position, the output should be

    L = [1,8,5,12,9,16]

      

I am focused on where to start, I have to use indexing and a for loop, but everything I try doesn't work. That's what I have so far

def main():
    L = [3,12,9,5,7,6,8]
    i=0
    while i < len(L):
      if i%2 == 1:
         print L[i]
         i = i+5
       elif i%2 == 0:
         print L

      

+3


source to share


6 answers


You can use a list comprehension , one of the greatest features of python:

L = [1,3,5,7,9,11]
L2 = [L[i]+5 if i%2 else L[i] for i in range(0,len(L))]

      



or, as @matiasg suggested:

L2 = [L[i] + 5 * (i % 2) for i in range(len(L))]

      

+2


source


You can link your list. Crossing assigns indices to your original list from another list of sources. This "other source list" can come from a simple list comprehension that is formed from another fragment.

>>> L = [1,3,5,7,9,11]
>>> L[1::2] = [x+5 for x in L[1::2]]
>>> L
[1, 8, 5, 12, 9, 16]

      


Description of the slicing syntax

Slicing is when you take a final sequence and index it with 1-2 colon characters to select a subsequence. A slice with 1 colon character has the format:

[start:stop]

      

A slice with two colons has the format:

[start:stop:step]

      



Arguments can be omitted and then set to their default values. If start is omitted, it defaults to the first index of the sequence, or 0, since Python sequences are 0-indexed. If stop is not specified, it defaults to the last valid sequence index + 1, or equivalently the sequence length. If step is omitted, it defaults to 1.

So when you make a slice of type seq[1::2]

, you say, get items seq

at indices starting at index 1 inclusive (specified by you), stopping at index len(seq)

exclusive (default value), and step by step 2 each time (specified by you).


Help understanding description

A list comprehension can be thought of as a concise, Pythonic way of doing display and filtering operations on an arbitrary number of potentially nested iterations over the iterations. If none of this makes sense to you, don't worry! You can find out all the data about the card and movies later. For now, just think about understanding the list [x+5 for x in L[1::2]]

as:

newlist = []
for x in L[1::2]:
    newlist.append(x+5)

      

And then the newlist

list comprehension value will be set.

+8


source


Or if you just want to change your own code:

def main():
    L = [3,12,9,5,7,6,8]
    i=0
    while i < len(L):
        if i%2 == 1:
            print L[i]
            // i= i+5
            L[i] = L[i]+5
        elif i%2 == 0:
            print L

      

The mistake you made was you changed the temporary variable i instead of the list item.

0


source


You are very close: if you want to go with your code, it is better to iterate over the list using for

in your case. Also, you first print the value and then increment it - so the printable value won't change.

The improved code looks like this:

def main():
    L = [3,12,9,5,7,6,8]
    for i in L:
        if i%2 == 1:
            print i + 5
        elif i%2 == 0:
            print i

      

0


source


Displaying a function for each odd index item will also work:

>>> L = [1,3,5,7,9,11]
>>> L[1::2] = map(lambda x: x + 5, L[1::2])
>>> L
[1, 8, 5, 12, 9, 16]

      

@ Shashank's answer is the way I'll do it, it's just that you know another way.

0


source


The most readable solution to this problem without creating a new list or using list validation would be to use an enumeration.

l = [1, 3, 5, 7, 9, 11]

for i, v in enumerate(l):  # i,v = index, value
    if i % 2 != 0:         # if the index is odd
        l[i] = v + 5       # add 5 to the value
print(l)

      

0


source







All Articles