我有一个输入整数值的元组,其值为high。我想循环遍历并取出元组中 >= 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)
最佳答案
您可以使用 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)]
关于python - 循环元组并获取从高到低的转换列表的更有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55328902/