【问题标题】:Compare two lists to find identical values, return the missing value比较两个列表以找到相同的值,返回缺失值
【发布时间】:2017-11-03 16:55:20
【问题描述】:

我的程序是遍历坐标(列表)并检查 3 个坐标是否从 ocoords(列表)中得出 True 并返回或可能得到该 False 值(坐标)

我试图找到一种有效的方法来在两个结构不同但坐标相同的列表中查找相似值。

coordinates = [[(2,2),(3,2)],[(2,2),(2,3)],[(4,2),(5,2)],[(5,2),(6,2)]]


#iterating through coordinates...
>>>
[(2, 2), (3, 2)]
[(2, 2), (2 ,3)]
[(4, 2), (5, 2)]
[(5, 2), (6, 2)]

那么我的下一个列表的结构是这样的(指定的坐标应该放在一起......

ocoords = [[[(2,2),(3,2)],[(2,2),(2,3)],[(4,2),(5,2)],[(3,3),(3,2)]], <-- last value is not identical
 [[(3,2),(4,2)],[(3,2),(3,3)],[(3,3),(4,3)],[(4,3),(4,2)]]] <-- structure of list

那么你会怎么做呢?我是新手,很抱歉这个问题。我曾想过使用布尔值,但我需要得到那个值为 False 的值。

我想看看是否有任何坐标在 ocoords [0] 中,如果是,但没有给我那个值。

【问题讨论】:

  • 返回值是什么还不是很清楚。而ocoords'结构的描述也不清楚。
  • 我想看看是否有任何坐标在 ocoords [0] 中,如果有,但没有给我那个值。
  • 您应该将其添加为问题的一部分。顺便说一句,项目的顺序是否始终如您的示例中那样对齐,或者可能是任意的?
  • 您可以轻松地zip 项目并成对比较,直到如果项目对齐,条件失败。如果不是,那将是完全不同的方法。
  • 谢谢,我试试看

标签: python loops


【解决方案1】:

您可以将itertools.dropwhile谓词 一起使用,以检查coordinates 中也包含在ocoords[0] 中的项目:

from itertools import dropwhile

val = next(dropwhile(lambda x: x in ocoords[0], coordinates))
print(val)
# [(5, 2), (6, 2)]

如果项目是对齐的,您可以使用zip 更快地进行,而不必检查每个项目的包含情况,而是检查直到出现成对的不匹配:

val = next(dropwhile(lambda x: x[0]==x[1], zip(coordinates, ocoords[0])))
print(val[0])  
# [(5, 2), (6, 2)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    相关资源
    最近更新 更多