Python在某些点跟踪列表中的索引 [英] Python keeping track of indices in lists at certain points

查看:161
本文介绍了Python在某些点跟踪列表中的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having some trouble with iteration and keeping track of various indices and values at different points in my list (I'm new to Python).

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

I am running a series of cycles, but want to determine their starts and end times. Experiments starts at around 0 and end at around 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]

以下是输出结果的示例:

Here is an example of what the output should look like:

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进行排序。

One approach I can think of is to sort the c.

c.sort()

这至少会将所有起始值放在列表的开头,将结束值放在列表的末尾。然而,那时我会忘记他​​们原来的指数。有人知道另一种方法吗?

This will at least put all the start values at the beginning of the list and the end values at the end of the list. However, then I would lose track of their original indices. Anyone know of another approach?

编辑:

这是我到目前为止,如果有人可以提供帮助的话修改,它会很棒:

This is what I have so far, if anyone can help modify, it would be great:

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


推荐答案

我将任务分开,建立字典 D 增加序列

I divide up the task, build a dictionary, D of the increasing sequences

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 我需要更宽的行限制

to print the dict D nicely in my IDE I needed wider line limit

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)]}

这篇关于Python在某些点跟踪列表中的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆