在Python的重复列表中跟踪值更改 [英] Track value changes in a repetitive list in Python
问题描述
我有一个包含重复值的列表,如下所示:
I have a list with repeating values as shown below:
x = [1, 1, 1, 2, 2, 2, 1, 1, 1]
此列表是从匹配正则表达式的模式(此处未显示)生成的.该列表保证具有重复值(很多重复,很多-数百个,如果不是数千个),并且永远不会随机排列,因为正则表达式每次都匹配.
This list is generated from a pattern matching regular expression (not shown here). The list is guaranteed to have repeating values (many, many repeats - hundreds, if not thousands), and is never randomly arranged because that's what the regex is matching each time.
我想要的是 跟踪条目从前一个值开始更改的列表索引 .因此对于上面的列表x
,我想获取一个更改跟踪列表[3, 6]
,该列表指示x[3]
和x[6]
与列表中的先前条目不同.
What I want is to track the list indices at which the entries change from the previous value. So for the above list x
, I want to obtain a change-tracking list [3, 6]
indicating that x[3]
and x[6]
are different from their previous entries in the list.
我设法做到了,但是我想知道是否有更清洁的方法.这是我的代码:
I managed to do this, but I was wondering if there was a cleaner way. Here's my code:
x = [1, 1, 1, 2, 2, 2, 1, 1, 1]
flag = []
for index, item in enumerate(x):
if index != 0:
if x[index] != x[index-1]:
flag.append(index)
print flag
输出:[3, 6]
问题:是否有一种更简洁的方法可以用更少的代码行来完成我想做的事情?
Question: Is there a cleaner way to do what I want, in fewer lines of code?
推荐答案
可以使用列表理解功能和range
函数
It can be done using a list comprehension, with a range
function
>>> x = [1, 1, 1, 2, 2, 2, 3, 3, 3]
>>> [i for i in range(1,len(x)) if x[i]!=x[i-1] ]
[3, 6]
>>> x = [1, 1, 1, 2, 2, 2, 1, 1, 1]
>>> [i for i in range(1,len(x)) if x[i]!=x[i-1] ]
[3, 6]
这篇关于在Python的重复列表中跟踪值更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!