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

2024-06-01 11:46:21 发布

您现在位置: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

Tags: 方法列表indexifvalueminstartmax
3条回答

我划分任务,构建一个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中很好地打印dictD,我需要更宽的行限制

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如下:Iterate over all pairs of consecutive items from a given list

为了跟踪列表索引,还可以使用^{}

所以这里有一个方法来获取所有开始/结束位置的索引/值。你知道吗

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

相关问题 更多 >