Python:根据元组列表中上一项的总和删除下一项

时间:2019-02-28 06:43:37

标签: python python-3.x list tuples

我有三个元组的示例输入列表:

bc_lst = [(639, 16), (653, 25), (734, 33), (768, 50), (777, 16), (827, 42), (854, 24), (867, 63), (869, 48), (877, 26), (903, 26), (927, 26), (929, 22), (949, 20), (969, 20), (990, 19), (999, 23), (1010, 19), (1030, 20), (1042, 63), (1049, 20), (1069, 17), (1143, 18), (1158, 18), (1174, 25)]

uc_lst = [(1215, 25), (1293, 25), (1317, 29), (1327, 43), (1346, 26), (1374, 26), (1400, 21), (1420, 21), (1430, 102), (1443, 20), (1465, 19), (1486, 20), (1506, 21), (1528, 20), (1549, 20), (1570, 20), (1591, 20), (1612, 16), (1621, 26), (1632, 21), (1639, 26), (1653, 21)]

dt_lst = [(1566, 39), (1609, 24), (1620, 20), (1650, 38), (1658, 20), (1691, 37), (1701, 20), (1732, 38), (1772, 16), (1785, 19), (1814, 36), (1854, 37), (1854, 38), (1861, 19)]

和一个缓冲区变量buf = 5。我想对bc_lstuc_lstdt_lst进行此操作:从第一项开始检查,如果元组的总和小于下一个元组的第一个元素的总和然后缓冲区从列表中删除下一个项目,并检查下一个列表项目。

考虑bc_lst。第一个元组的总和是655653+5 > 655,因此我们保留(653,25)。现在检查是否为734 +5 > 653+25的{​​{1}},因此请保留True。现在检查(734,33),它也是768 +5 > 734+33,所以我们检查下一个项目,但是True777 +5 > 768+50,因此我们删除了元组False。现在我们再次检查(777,16)是否为827+5 > 768+50,因此我们保留True。该过程继续进行。

这是我尝试过的代码:

(827,42)

我为bc_lst获得的输出是:

def func1(a1):
    count = 0
    while count < len(a1)-1:
        if a1[count+1][0] + buf < sum(a1[count]):
            del a1[count+1]
        count +=1
func1(bc_lst)

,对于uc_lst,输出为:

[(639, 16), (653, 25), (734, 33), (768, 50), (827, 42), (867, 63), (877, 26), (903, 26), (927, 26), (949, 20), (969, 20), (990, 19), (1010, 19), (1030, 20), (1049, 20), (1069, 17), (1143, 18), (1158, 18), (1174, 25)]

,对于dt_lst,输出为:

[(1215, 25), (1293, 25), (1317, 29), (1346, 26), (1374, 26), (1400, 21), (1420, 21), (1443, 20), (1465, 19), (1486, 20), (1506, 21), (1528, 20), (1549, 20), (1570, 20), (1591, 20), (1612, 16), (1632, 21), (1653, 21)]

[(1566, 39), (1609, 24), (1650, 38), (1691, 37), (1732, 38), (1772, 16), (1785, 19), (1814, 36), (1854, 37), (1861, 19)] 的期望输出是:

bc_lst

[(639, 16), (653, 25), (734, 33), (768, 50), (827, 42), (867, 63), (927, 26), (949, 20), (969, 20), (990, 19), (1010, 19), (1030, 20), (1049, 20), (1069, 17), (1143, 18), (1158, 18), (1174, 25)] 的期望输出与我得到的输出相同,uc_lst的期望输出为:

dt_lst

代码有什么问题?

2 个答案:

答案 0 :(得分:2)

我认为问题在于,如果您删除一个项目,就不想增加计数。

buf=5

def func1(a1):
    count = 0
    while count < len(a1) - 1:
        if a1[count + 1][0] + buf < sum(a1[count]):
            del a1[count + 1]
        else:
            count += 1

答案 1 :(得分:2)

要保存中间结果,您可以一一处理元素。

例如,您将具有一个函数,其中输入作为要处理的列表,要进行缓冲和当前的处理元素索引,如下所示:

def process_list_element(list, current_index, buffer):
    if list[current_index + 1][0] + buf < sum(list[current_index]):
        del list[current_index+ 1]
    else:
        current_index += 1
    return list, current_index

*请仔细查看,因为它只是伪代码来演示该方法

然后重复

index = 0
buffer = 5
while index < len(list) -1:
    list, index = process_list_element(list, index, buffer)