gpt4 book ai didi

python-3.x - 如何返回Python列表中组的最后一个索引

转载 作者:行者123 更新时间:2023-12-02 02:45:02 26 4
gpt4 key购买 nike

我有一个以下形式的列表:

[0, 0, 0, 0, 1, 1, 1, 0.6, 0.6, 0, 0, 0]

列表中的每一项都是一个小十进制数。我正在寻找一种返回每个组的最后一个索引位置的方法。在上面的例子中,它会是这样的:

0: 3, 1: 6, 0.6: 8, 0: 11

我对 python 还很陌生,我真的不知道如何解决这个问题

最佳答案

itertools.groupby在这里可能很有用,它处理几乎所有事情,除了跟踪索引,这对你自己来说并不难:

import itertools

a = [0, 0, 0, 0, 1, 1, 1, 0.6, 0.6, 0, 0, 0]
i = 0
for val, group in itertools.groupby(a):
for inst in group:
# each element that is the same in sequence, increment index
i += 1
# after the inner for loop i will be the index of the first element of next group
# so i - 1 is the index of last occurence.
print(val, i - 1)

如果你特别擅长enumeratevariable unpacking你可以把它做得非常短,尽管它是如何工作的不太明显。

import itertools
from operator import itemgetter

a = [0, 0, 0, 0, 1, 1, 1, 0.6, 0.6, 0, 0, 0]
# still group only by value but now use enumerate to have it keep track of indices
for val, group in itertools.groupby(enumerate(a), itemgetter(1)):
# this is tuple unpacking, irrelevant is a list of values that aren't the last one, and last is the one we care about.
[*irrelevent, last] = group
print(last)

这个答案并不是说“你应该这样做”,而是说“这是Python中存在的一些东西”,快乐编码:)

关于python-3.x - 如何返回Python列表中组的最后一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62942113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com