【问题标题】:Python - checking if element is in list of lists (pythonic way) [duplicate]Python - 检查元素是否在列表列表中(pythonic方式)[重复]
【发布时间】:2015-03-20 13:49:32
【问题描述】:

假设我有一个按如下方式初始化的列表“图表”。

graph = [[1, 2, 3], [2, 3, 4], [3, 5, 7]]

然后我将如何确定 1 是否在图中?

有没有比做类似的更简单、更优化的方法,

in_graph = False
for row in graph:
    if 1 in row:
        in_graph = True
        break

?

谢谢,

滚刀

【问题讨论】:

标签: python arrays list search


【解决方案1】:

您可以将any 与生成器表达式一起使用。

any(1 in g for g in graph)

【讨论】:

    【解决方案2】:

    试试

    any(x in row for row in graph)
    

    x 是您要查找的元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-06
      • 2012-04-03
      • 2020-06-25
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多