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

标签 python list loops for-loop tuples

我有一个输入整数值的元组,其值为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/

相关文章:

python - 如何将数据集拆分为训练集和验证集并保持类之间的比例?

python re如何在特定单词后留出空间?

c# - 在 C# 中将列表转换为字符串

python - 循环列表比循环 ndarray 快 20 倍

c - 字符串和无限循环中的堆栈粉碎

python - 对象不支持项目分配错误

Python 相当于 SQL Rank

python - 用于评估的 Tensorflow 平均绝对误差 (MAE)

c# - 如何查找 List 在 List<string> 中有重复值

javascript - 将值传递给 onclick