【问题标题】:Python: Trying to get index of an intersection [duplicate]Python:试图获取交叉点的索引[重复]
【发布时间】:2012-09-25 15:30:12
【问题描述】:

可能重复:
Python: Finding corresponding indices for an intersection of two lists

我有以下代码行:

for i in [i for i,x in enumerate(catdate) if x == set(NNSRCfile['datetimenew']).intersection(catdate)]:
    print i

我正在尝试查找上述两个组件的交集索引。两者都是有几个共同点的冗长列表。相交部分完美运行;但是,for 循环似乎什么也没输出。 (即:没有打印任何内容)。

Python 没有输出错误,当我在 IPython 中运行代码时,我注意到 i 等同于列表“catdate”中的最后一个元素,而不是列出等同于交点值。

非常感谢任何帮助!

【问题讨论】:

  • 这和你昨天的帖子有什么不同吗?
  • 是的,虽然是同样的问题。不过我正在尝试一种不同的方法。
  • 您确定不想使用x in ... 来测试x 是否在您的路口?
  • @Pierre,您的意思是使用“x in”而不是“x ==”?
  • 你知道 .intersection 没有(逻辑上)做任何事情,因为我们知道 x 在 catdate 中,你只需要测试 x 是否在 set(NNSRCfile['datetimenew']) 中。不过,预先计算交叉点可能会更有效。

标签: python indexing set-intersection


【解决方案1】:

如果你想测试x是否在你的路口,你应该使用:

indices = [i for (i, x) in enumerate(catdate) if x in set(NNSRCfile['datetimenew']).intersection(catdate)]
for i in indices:
    print i

否则,您将单个元素与一个集合进行比较,这不太可能起作用(因此,测试总是失败,您的 indices 列表为空,没有任何内容被打印...

【讨论】:

  • 我认为这解决了我的问题。我不知道你能不能“如果......在......”非常感谢你的帮助。 :)
  • @user1620716 很高兴为您提供帮助。熟能生巧,继续努力!
【解决方案2】:

set() 不会匹配单个值,试试:

if set(x) == set( ...

我个人会避免在这样的嵌套上下文中使用相同的“i”,顺便说一句,尽管 python alloqws 它。至少读起来很混乱..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-07
    • 2020-06-21
    • 2012-07-14
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    相关资源
    最近更新 更多