循环遍历元组并获取从高到低的转换列表列表的更有效方法



我有一个输入整数值的元组,和一个的值。我想遍历并拉出元组中>= 高值的第一个实例的对,然后是<<em>高的第一个值。 一个例子可能会有所帮助:

仅保留每个重复高点或低点的第一个高点或第一个低点

例如,如果 max == 100,并且输入为 (102, 109, 120, 80, 40, 30, 20090(

输出应为 [[102, 80], [200, 90]]

items = (102, 109, 120, 80, 40, 30, 200, 90)
high = 100
started = False  # Used to ensure we start with high values first
currently_on_highs = True
first_val_high = True
first_val_low = True
transitions = []
inner_transition = []
for item in items:
    if item >= high:
        started = True
        currently_on_highs = True
        if first_val_high:
            first_val_high = False
            first_val_low = True
            inner_transition.append(item)
    else:
        if started:
            currently_on_highs = False
            if first_val_low:
                first_val_high = True
                first_val_low = False
                inner_transition.append(item)
                transitions.append(inner_transition)
                inner_transition = []
print(transitions)

在@michael-butscher的建议下,这是一个更好的结果

items = (102, 109, 120, 80, 40, 30, 200, 90)
high = 100
in_high = False
transitions = []
inner_transition = []
for item in items:
    if item >= high and not in_high:
        in_high = True
        inner_transition.append(item)
    elif item < high and in_high:
        in_high = False
        inner_transition.append(item)
        transitions.append(inner_transition)
        inner_transition = []
print(transitions)

您可以使用zip轻松执行此操作,方法是将元素偏移一个条目,以将每个元素与其前身进行比较:

items  = (102, 109, 120, 80, 40, 30, 200, 90)
high   = 100
bounds = [ num for prev,num in zip((high-1,)+items,items) if (num<high)^(prev<high) ] 
result = list(zip(bounds[::2],bounds[1::2]))
print(result) # [(102, 80), (200, 90)]

你来了:

items = (102, 109, 120, 80, 40, 30, 200, 90)
high = 100
ret = []
findh = True
for i in items:
    if findh and i >= high:
        findh = False
        ret.append([i])
    elif not findh and i < high:
        findh = True
        ret[-1].append(i)
print(ret)

解释:

  • ret = []我们将对添加到什么
  • findh = True我们是否应该寻找更高的价值
  • if findh and i >= high:如果我们看得更高并且更高
    • findh = False未来看起来更低
    • ret.append([i])将另一个列表添加到我们的主列表中,其中只有这个值
  • elif not findh and i < high:如果我们看起来更低,它更低
    • findh = True未来看得更高
    • ret[-1].append(i)将此值添加到主列表中的最后一个列表

第一步可能是创建所有"开关"值的列表:

items = (102, 109, 120, 80, 40, 30, 200, 90)
high = 100
res = []
last = high-1
for x in items:
    if last < high <= x or x <= high < last: 
        res.append(x) 
    last = x

然后,您可以构建对:

res = [(res[i], res[i+1]) for i in range(0, len(res), 2)]

最新更新