本文介绍了编辑列表中每第N个项目的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对列表中的每个第n个值执行算术运算的最Python方式是什么?例如,如果我以list1开头:

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]

我想在第二个项目中添加1,这样可以得出:

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

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

我尝试过:

list1[::2]+1

还有:

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

推荐答案

您可以将slicing与列表理解一起使用,如下所示:

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]

这篇关于编辑列表中每第N个项目的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 19:47