循环通过元组并获得从高到低的转换列表的更有效方式

问题描述 投票:1回答:3

我有一个输入整数值元组和一个高值。我想循环并拉出元组中第一个值为> = high的值的第一个实例,然后是第一个<high的值。一个例子可能有帮助:

只保留每个重复高或低的第一个高位或第一个低位

例如,如果max == 100,则输入为(102,109,120,80,40,30,200,90)

输出应该是[[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)
python list loops for-loop tuples
3个回答
1
投票

您可以通过将元素偏移一个条目来轻松地使用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)]

0
投票

干得好:

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我们是否应该寻求更高的价值
  • qazxsw poi如果我们看起来更高而且更高 qazxsw poi将来会看起来更低 if findh and i >= high:将另一个列表添加到我们的主列表中,只有这个值
  • findh = False,如果我们看起来更低,它更低 ret.append([i])将来看起来更高 elif not findh and i < high:将此值添加到主列表中的最后一个列表

0
投票

第一步可能是创建所有“切换”值的列表:

findh = True

然后你可以建立对:

ret[-1].append(i)
© www.soinside.com 2019 - 2024. All rights reserved.