【问题标题】:How to check if two same values in 2 lists return true using Python [duplicate]如何使用Python检查2个列表中的两个相同值是否返回true [重复]
【发布时间】:2019-08-10 08:17:39
【问题描述】:

我有 2 个像素坐标列表

(confirmed pixel[(60, 176), (60, 174), (63, 163), (61, 176)] & 
white_pixel [(64, 178), (60, 174), (61, 176)])

我想比较它们,如果发现任何相同的值,例如 (61, 176)(60, 174),它将返回True,表示至少需要匹配一个值。

我怎样才能在这个 if 语句中做到这一点?

confirmed_pixel == white_pixel 不能作为 all 两个列表中的值必须相同才能返回 true

if confirmed_pixel == white_pixel and len(confirmed_pixel) != 0 and len(white_pixel) != 0:
    print("True")
    continue

【问题讨论】:

  • 你可以用循环来做到这一点。
  • 您有两个listtuples。使用loop 将第一个list 中的每个tuple 与第二个list 中的所有其他tuples 进行比较。在相等的情况下可以printTrue
  • 您好 Cytex,欢迎来到 SO。使用谷歌搜索很容易在 SO 上找到您的问题的重复项 - 我使用了这个:python check if two lists share elements 作为谷歌查询...

标签: python python-3.x list


【解决方案1】:

为此使用sets,这是有效测试交叉口的唯一方法。 :

confirmed = [(60, 176), (60, 174), (63, 163), (61, 176)]
white = [(64, 178), (60, 174), (61, 176)]

要获得交点:

print(set(confirmed).intersection(white))
# {(60, 174), (61, 176)}

要获得TrueFalse,只需将结果集转换为bool:空集为假,非空集为真:

print(bool(set(confirmed).intersection(white)))
# True

另一个例子,有空的交叉点:

confirmed = [(60, 176), (600, 174), (63, 163), (6100, 176)]
white = [(64, 178), (60, 174), (61, 176)]


print(set(confirmed).intersection(white))
# set()
print(bool(set(confirmed).intersection(white)))
# False

【讨论】:

    【解决方案2】:

    这将为您完成预期的工作

    if any([x==y for x in confirmed_pixel for y in white_pixel]):
        return True
    

    【讨论】:

      猜你喜欢
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-11
      相关资源
      最近更新 更多