简体   繁体   English

遍历Python列表中的元素范围

[英]Iterate through ranges of elements in a list in Python

I am a beginner in Python and I have a doubt about iterating through a range of elements in a list. 我是Python的初学者,我对遍历列表中的一系列元素有疑问。

I have this list: 我有这个清单:

['0.95', '0.05', '0.94', '0.06', '0.29', '0.71', '0.001', '0.999']

Suppose that, starting in the first position, I want to iterate through ranges of two elements: substituting the first two, leaving the next two as they were, and then substituting again the next two: 假设从第一个位置开始,我要遍历两个元素的范围:替换前两个元素,保留下两个元素,然后再次替换下两个元素:

[-, -, '0.94', '0.06', -, -, '0.001', '0.999']

I also want to be able to start at any position. 我也希望能够从任何位置开始。 For example, using the same range as before, but starting in the third position: 例如,使用与以前相同的范围,但从第三个位置开始:

['0.95', '0.05', -, -, '0.29', '0.71', -, -]

I have tried range with three parameters, but it only substitutes the first position in the range, not all the elements in the range. 我尝试了使用三个参数的range,但是它仅替换范围中的第一个位置,而不替换范围中的所有元素。

l = ['0.95', '0.05', '0.94', '0.06', '0.29', '0.71', '0.001', '0.999']

def subDashes(l, start):
    newL = []
    for index, elem in enumerate(l):
        if index%4 == start or index%4 == start+1:
            newL.append('-')
        else:
            newL.append(elem)
    return newL

>>> subDashes(l, 0)
['-', '-', '0.94', '0.06', '-', '-', '0.001', '0.999']

>>> subDashes(l, 1)
['0.95', '-', '-', '0.06', '0.29', '-', '-', '0.999']

>>> subDashes(l, 2)
['0.95', '0.05', '-', '-', '0.29', '0.71', '-', '-']

The simplest, and I think the best, way to do this is like this: 我认为最简单的方法是这样的:

seq = [1,2,3,4,5,6,7,8]

replace_list= ['-','-','-','-']

seq[::4] = replace_list[::2]
seq[1::4] = replace_list[1::2]

print seq

Output: 输出:

['-', '-', 3, 4, '-', '-', 7, 8]

To start in which item to start just do: 要开始从哪个项目开始,请执行以下操作:

replace_list= ['-','-','-']

starting_item=3
seq[starting_item::4] = replace_list[::2]
seq[starting_item+1::4] = replace_list[1::2]

Note that replace_list has to have the specific number of elements you want to substitute in seq list. 请注意,replace_list必须具有要在seq列表中替换的元素的特定数量。

Output: 输出:

[1, 2, 3, '-', '-', 6, 7, '-']

If you want to replace all items always with same value, you can do: 如果要始终用相同的值替换所有项目,则可以执行以下操作:

starting_item=3

last_part = min((len(seq) - starting_item) % 4, 2)
size = ((len(seq) - starting_item)/4) * 2 + last_part
replace_list= ['-']*size

Replace start with the required starting value. 将start替换为所需的起始值。

l = ['0.95', '0.05', '0.94', '0.06', '0.29', '0.71', '0.001', '0.999']


def dash(l,start):
    for i in range(start,len(l)):
        if (i - start) % 4 == 0 or (i - start) % 4 == 1:
            l[i] = '-'
    return l

print dash(l,start = 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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