Possible Duplicate:
Python: Finding corresponding indices for an intersection of two lists

I have the following line of code:

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

I am trying to find the index of the intersection for the two components above. Both are lengthy lists that have several commonalities. The intersection part works perfectly; however, the for loop seems to output nothing. (ie: there is nothing that is printed).

Python outputs no error, and when I run the code in IPython, I notice that i is equivalent to to the very last element in the list "catdate", instead of listing the indices of "catdate" that are equivalent to the intersection values.

Any help is greatly appreciated!

有帮助吗?

解决方案

If you want to test whether x is in your intersection, you should use:

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

Otherwise, you're comparing a single element to a set, which is unlikely to work (therefore, the test always fail, your indices list is empty, nothing gets printed...

其他提示

set() will not match a single value, try:

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

Personally I'd avoid using the same "i" in nested contexts like that, btw, although python alloqws it. At least it is confusing to read..

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top