Python 在某些点跟踪列表中的索引



我在迭代和跟踪列表中不同点的各种索引和值时遇到了一些麻烦(我是 Python 的新手)。

我正在运行一系列周期,但想确定它们的开始和结束时间。实验从 0 左右开始,到 50 左右结束。

以下是周期列表的样子:

c = [0, 10, 11, 48, 50.5, 0.48, 17, 18, 23, 29, 33, 34.67, 50.1, 0.09, 7, 41, 45, 50]

下面是输出应如下所示的示例:

C 1:
Start: (0, 0) # starts at index 0, value 0
End: (4, 50.5) #ends at index 4, value 50.5
C 2:
Start: (5, 0.48)
End: (12, 50.1)
C 3:
Start: (13, 0.09)
End: (17, 50)

我能想到的一种方法是对 c 进行排序。

c.sort()

这至少会将所有起始值放在列表的开头,将结束值放在列表的末尾。但是,这样我就会忘记他们的原始索引。有人知道另一种方法吗?

编辑:

这就是我到目前为止所拥有的,如果有人可以帮助修改,那就太好了:

min = []
max = []
for i, (first,second) in enumerate(zip(c, c[1:])):
    print(i, first, second)
    if first < second:
        min.append(first)
        continue
    if first > second:
        max.append(first)
        continue
我划分

任务,构建一个dictionaryD递增序列

c = [0, 10, 11, 48, 50.5, 0.48, 17, 18, 23, 29, 33, 34.67, 50.1, 0.09, 7, 41, 45, 50]
D, k = {0: []}, 0
for i, (first, second) in enumerate(zip(c, [0] + c)):
    if first >= second:
        D[k].append((i, first))  # adding increasing to value list in current D[k]
    else:
        k += 1
        D[k] = [(i, first)]  # initializing new D[k] for next sequence

然后以所需的格式打印

for k in D:  # sorted(D) safer, dict doesn't guarantee ordering, works here  
    print('C {0}:'.format(k))
    print('Start {0}'.format(D[k][0]))
    print('End   {0}'.format(D[k][-1]), 'n')
C 0:
Start (0, 0)
End   (4, 50.5) 
C 1:
Start (5, 0.48)
End   (12, 50.1) 
C 2:
Start (13, 0.09)
End   (17, 50) 

为了在我的 IDE 中很好地打印字典D我需要更宽的行限制

import pprint
pp = pprint.PrettyPrinter(width=100)
pp.pprint(D)
{0: [(0, 0), (1, 10), (2, 11), (3, 48), (4, 50.5)],
 1: [(5, 0.48), (6, 17), (7, 18), (8, 23), (9, 29), (10, 33), (11, 34.67), (12, 50.1)],
 2: [(13, 0.09), (14, 7), (15, 41), (16, 45), (17, 50)]}

假设您的起始值是列表的最小值,结束值是列表的最大值,这里有一种方法可以做到这一点:

(start_val,end_val) = (min(c),max(c))
(start_ind,end_ind) = (c.index(start_val),c.index(end_val))

这也假设最小值和最大值没有重复项,或者如果有重复项,则可以获取第一个元素的索引,因为 index() 函数仅返回它找到的第一个元素等于参数的索引。更多信息: https://docs.python.org/3.6/library/stdtypes.html#typesseq

您的列表具有递增的序列,因此更改位于数字大于其下一个数字的位置。要比较列表中所有连续对,您可以使用如下所示zip: 迭代给定列表中所有连续项目对

此外,要跟踪列表索引,您可以使用enumerate

因此,这是一种获取所有开始/结束位置的索引/值的方法。

circle=0
for i, (first,second) in enumerate(zip(c, c[1:])):
    if i==0:
        circle +=1
        print("nC", circle, "nStart:", i, first)
    elif i==len(c)-2:
        print("End:", i+1, second)
    elif first > second:
        print("End:", i, first)
        circle +=1
        print("nC", circle, "nStart:", i+1, second)

输出:

C 1 
Start: 0 0
End: 4 50.5
C 2 
Start: 5 0.48
End: 12 50.1
C 3 
Start: 13 0.09
End: 17 50

最新更新