繁体   English   中英

将元组列表转换为列表,修改它,然后将其转换回来

[英]Conver a list of tuple to list, modify it , then convert it back

我想写一个 function,我想从第二个参数中删除重叠间隔。 参数(元组列表)为 integer 区间,例如:[(8, 23)]。 如果它与第一个参数重叠,则结束,从中删除重叠间隔。 例如:如果第一个参数是[(0, 10)],第二个是[(8, 23)],我想把第二个参数改成[(11, 23)]。 我试过这样:

def remove_overlapping_products(brand_positions, product_positions):
brand_pos_list = list(brand_positions)
product_pos_list = list(product_positions)

    
def check_overlap(brand_pos_list, product_pos_list):
    if product_pos_list[0]>= brand_pos_list[0] and product_pos_list[0]<= brand_pos_list[1]:
        product_pos_list[0] =  brand_pos_list[1]-1
        return True
    if product_pos_list[1]>= brand_pos_list[0] and product_pos_list[1]<= brand_pos_list[1]:
        product_pos_list[1] =  brand_pos_list[0]-1
        return True

   

for x in brand_pos_list:
    for y in product_pos_list:
        check_overlap(x, y)
         

                            
product_positions_new = tuple(product_pos_list)                
            
return [pos for pos in product_positions_new]

但我收到错误消息:“'tuple' object 不支持项目分配”。 由于我使用了转换后的列表,因此我无法理解此消息的原因。

有人可以帮我写代码吗?

如果您只想更改第二个参数,它可以是一个更短的解决方案:

def check_overlap(x,y):
    return True if x[1]>=y[0] else False
     
def remove_overlap(brand_positions, product_positions):
    return [(x[1]+1, y[1]) if (check_overlap(x, y) and x[1]<y[1]) else y for (x, y) in zip(brand_positions, product_positions)]

例子:

X = [(0,10), (2,5), (6,9)]
Y = [(8,23), (5,7), (1,7)]

print(remove_overlap(X,Y))

Output:

[(11, 23), (6, 7), (1, 7)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM