Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Friday, March 18, 2016

Edit the value of every Nth item in a list

Edit the value of every Nth item in a list


What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1:

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  

I would like to add 1 to every second item, which would give:

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

I've tried:

list1[::2]+1  

and also:

for x in list1:      x=2              list2 = list1[::x] + 1  

Answer by Bhargav Rao for Edit the value of every Nth item in a list


Use enumerate and a list comprehension

>>> list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  >>> [v+1 if i%2!=0 else v for i,v in enumerate(list1)]  [1, 3, 3, 5, 5, 7, 7, 9, 9, 11]  

Answer by gtlambert for Edit the value of every Nth item in a list


You could use slicing with a list comprehension as follows:

In [26]: list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]    In [27]: list1[1::2] = [x+1 for x in list1[1::2]]    In [28]: list1  Out[28]: [1, 3, 3, 5, 5, 7, 7, 9, 9, 11]  

Answer by Divisadero for Edit the value of every Nth item in a list


list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  for i in range(1, len(list1), 2):      list1[i] +=1  print(list1)  

using i%2 seems not very efficient

Answer by soon for Edit the value of every Nth item in a list


numpy allows you to use += operation with slices too:

In [15]: import numpy as np    In [16]: l = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])    In [17]: l[1::2] += 1    In [18]: l  Out[18]: array([ 1,  3,  3,  5,  5,  7,  7,  9,  9, 11])  

Answer by Tóth József for Edit the value of every Nth item in a list


Try this:

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  for i in range(1,len(list1),2):      list1[i] += 1  

Answer by QuestionC for Edit the value of every Nth item in a list


You can create an iterator representing the delta (itertools.cycle([0, 1]) and then add its elements to your existing list.

>>> list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  >>> [a + b for a,b in zip(list1, itertools.cycle([0,1]))]  [1, 3, 3, 5, 5, 7, 7, 9, 9, 11]  >>>  

Answer by Derrick Yang for Edit the value of every Nth item in a list


a = [i for i in range(1,11)]   #a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  b = [a[i]+1 if i%2==1 else a[i] for i in range(len(a))]   #b = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11]  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.