比较x和y坐标并从元组列表列表中删除元素

时间:2017-03-27 04:36:12

标签: python list iteration tuples

我有一个列表'u',其中包含一组列表,其中包含元组(x,y)。作为一个更大问题的一部分,我得到了一个列表,我试图将元组列表中的每个元组元素与列表“u”中其他元组列表中的元素进行比较,以便:我需要比较一个元素,例如:属于u [0]列表的(3,10)将与列表u [1],u [2],u [3]中具有相同x坐标的元素进行比较...并且由于X坐标相等,包含最高y坐标的元素在其列表中存活,但是y坐标最小的元素应该被消除。

u = [[(2, 10), (3, 10), (4, 10), (5, 10), (6, 10), (7, 10), (8, 10), (9, 10)],
 [(3, 15), (4, 15), (5, 15), (6, 15), (7, 15)],
 [(5, 12), (6, 12), (7, 12), (8, 12), (9, 12), (10, 12), (11, 12), (12, 12)],
 [(15, 10), (16, 10), (17, 10), (18, 10), (19, 10), (20, 10)],
 [(19, 8), (20, 8), (21, 8), (22, 8), (23, 8), (24, 8)]]

(3,10) of u[0] compared against (3,15) of u[1] => (3,15) survives and (3,10) gets eliminated from the list.

所以,我希望有人能为我提供一个更简单,更强大的pythonic解决方案。提前致谢

这就是我所做的:

def filterAllmax(self, u):
        u = [item for sub in u for item in sub]
        for i in range(len(u)):
            for j in range(i, len(u)):
                for k in u[i]:
                    if k[0][0] in u[j]:
                        m += [u[i] for i, v in enumerate(u[j]) if v[1] < k[0][1] # store the values that have y co-ordinates less than the value
        for i in m:
            u.remove(i)
        return u
  

注意:在发布我的查询之前,我已经搜索了stackoverflow   相关的解决方案,但我找不到符合我需求的解决方案。

1 个答案:

答案 0 :(得分:0)

我试着写一个Pythonic方式。

print {i1[0]: max(0,*(i[1] for i in sum(u, []) if i[0] == i1[0])) for i1 in sum(u, [])}

结果:

{2: 10, 3: 15, 4: 15, 5: 15, 6: 15, 7: 15, 8: 12, 9: 12, 10: 12, 11: 12, 12: 12, 15: 10, 16: 10, 17: 10, 18: 10, 19: 10, 20: 10, 21: 8, 22: 8, 23: 8, 24: 8}

sum(u, [])将嵌套列表转换为平面列表:

[(2, 10), (3, 10), (4, 10), (5, 10), (6, 10), (7, 10), (8, 10), (9, 10), (3, 15), (4, 15), (5, 15), (6, 15), (7, 15), (5, 12), (6, 12), (7, 12), (8, 12), (9, 12), (10, 12), (11, 12), (12, 12), (15, 10), (16, 10), (17, 10), (18, 10), (19, 10), (20, 10), (19, 8), (20, 8), (21, 8), (22, 8), (23, 8), (24, 8)]

然后迭代列表,使用max()获取最大值并使用dict理解返回结果。