list comprehention
Tim Chase
python.list at tim.thechases.com
Thu Jan 19 12:48:04 EST 2006
>> >Python beginner here and very much enjoying it. I'm looking
>> > for a pythonic way to find how many listmembers are also
>> > present in a reference list. Don't count duplicates (eg. if
[snipped]
> won't set remove duplicates which he wants to preserve ?
My reading was that the solution shouldn't count duplicates
("Don't count duplicates"). However, once you mentioned it, and
I saw other folks' responses that looked very diff. from my own,
I re-read the OP's comments and found that I missed this key bit:
"note that only the first *two* 2's count, the third 2
in the list should not be counted"
(*emphasis* mine)
and that the desired result was a count (though a len(Set())
would return the right count if the OP wanted the true
intersection, but that's beside the point).
My error. Sorry, ladies and gentlemen :)
I'm partial to the elegance of markscala's suggestion of:
len([ref.pop(ref.index(x)) for x in lis if x in ref])
though it might need to come with a caveat that it doesn't leave
"ref" in the same state is it was originally, so it should be
copied and then manipulated thusly:
r = ref[:]
len([r.pop(r.index(x)) for x in (lis if x in r])
which would then leave ref undisturbed. As tested:
import random
ref = [random.randint(1,5) for n in range(5)]
for x in range(1,10):
lis = [random.randint(1,5) for n in range(5)]
r = ref[:]
print repr((r,lis))
print len([r.pop(r.index(x)) for x in lis if x in r])
seems to give the results the OP describes.
-tim
More information about the Python-list
mailing list