[英]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? 对列表中的每个第n个值执行算术运算的最pythonic方法是什么? For example, if I start with list1:
例如,如果我从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: 我想在每个第二项添加1,这将给出:
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
You could use slicing
with a list comprehension as follows: 您可以使用
slicing
与列表推导,如下所示:
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]
Use enumerate
and a list comprehension 使用
enumerate
和列表理解
>>> 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]
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 使用i%2似乎效率不高
Try this: 尝试这个:
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(1,len(list1),2):
list1[i] += 1
You can create an iterator representing the delta ( itertools.cycle([0, 1])
and then add its elements to your existing list. 您可以创建表示delta的迭代器(
itertools.cycle([0, 1])
,然后将其元素添加到现有列表中。
>>> 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]
>>>
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.