【问题标题】:Python IN operator for List comparision用于列表比较的 Python IN 运算符
【发布时间】:2012-02-27 06:39:59
【问题描述】:

我正在使用 Python 插件。
我有一个名为 station_list 的列表,我已将所有值附加到该列表中。它包含所有整数值。
现在,我想用列表内容检查我的查询结果。我的代码是:

self.db._exec_sql(c, "select distinct (station) from station  ")
for row in c.fetchall():
    for m in range(len_station_list):
        print row[0],station_list[m]

        if row[0] == station_list[m]:
                print 'true'

我正在使用列表值检查每个选定的行。当我打印和检查时,它给出了正确的答案。但是比较出错了。
不满足条件if row[0] == station_list[m]:.
可能是什么问题?

【问题讨论】:

  • 您能否发布print row[0],station_list[m] 行的输出,以便我们了解if 失败的原因?

标签: python list contains


【解决方案1】:

试试这个。

x = self.db._exec_sql(c, "select distinct (station) from station  ").fetchall()

y = [p for p in x if p[0] in station_list]

【讨论】:

  • 感谢帮助..p[0] 只检查一行。如何检查所有行? y 包含什么??
  • @user1111283 这不是真的。 p[0] 检查每行的第一个成员(字段)。 y 包含第一个成员在 station_list 中的所有行 - 最好是 set,而不是列表。
  • @user1111283 [ ] 括号中的代码称为列表推导——它将遍历 x 中的所有项目并构建一个包含 p 中所有项目的列表,其中 p[0] 在 station_list 中。
猜你喜欢
  • 2021-04-30
  • 2019-09-29
  • 2021-09-02
  • 1970-01-01
  • 1970-01-01
  • 2012-10-14
相关资源
最近更新 更多