hcp*_*hcp 6 python indexing list
我有一个列表,看起来像:
mot = [0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,0,0,0]
我需要附加到一个列表,当元素从0to 1(而不是 from 1to 0)更改时的索引。
我试着做以下,但是当它发生变化,同时也注册1到0。
i = 0
while i != len(mot)-1:
if mot[i] != mot[i+1]:
mot_daily_index.append(i)
i += 1
Run Code Online (Sandbox Code Playgroud)
另外,但不是那么重要,是否有更干净的实现?
Ann*_*Zen 15
以下是如何使用列表理解来做到这一点:
mot = [0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,0,0,0]
mot_daily_index = [i for i,m in enumerate(mot) if i and m and not mot[i-1]]
print(mot_daily_index)
Run Code Online (Sandbox Code Playgroud)
输出:
[7, 24]
Run Code Online (Sandbox Code Playgroud)
list(enumerate([7,5,9,3]))将返回[(0, 7), (1, 5), (2, 9), (3, 3)],因此iini for i, m in enumerate是该m迭代期间的索引。使用带过滤器的列表理解来获取索引:
mot = [0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,0,0,0]
idx = [i for i,v in enumerate(mot) if i and v > mot[i-1]]
print(idx)
Run Code Online (Sandbox Code Playgroud)
输出:
[7, 24]
Run Code Online (Sandbox Code Playgroud)
你可以用
lst = [0, 0, 0, 1, 1, 1, 0, 1]
# 0 1 2 3 4 5 6 7
for index, (x, y) in enumerate(zip(lst, lst[1:])):
if x == 0 and y == 1:
print("Changed from 0 to 1 at", index)
Run Code Online (Sandbox Code Playgroud)
哪个产量
Changed from 0 to 1 at 2
Changed from 0 to 1 at 6
Run Code Online (Sandbox Code Playgroud)
这是itertools.groupby用于将列表分组为 0 和 1 的解决方案:
from itertools import groupby
mot = [0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,0,0,0]
mot_daily_index = []
l = 0
for s, g in groupby(mot):
if s == 1:
mot_daily_index.append(l)
l += len(list(g))
print(mot_daily_index)
Run Code Online (Sandbox Code Playgroud)
输出:
[7, 24]
Run Code Online (Sandbox Code Playgroud)