问题描述:

Take the following code:

a = [1,2,3,4]

if 1 in a or 2 in a:

print 'found'

Is there a cleaner/more elegant way of doing this? Perhaps:

a = [1,2,3,4]

b = [1,2]

if set(a) & set(b):

print found

网友答案:
a = [1,2,3,4]
b = [1,2]

print any(x in a for x in b)
True
网友答案:

Your second example based on set doesn't work because it will always return True for non-empty a/b. However sets are likely the right to use:

if set(b).issubset(set(a)):
    print "found"

Please note that b = set([]) is always a subset of set(a).

Update: I just noticed that you only want to know if any of the items in b is part of a which is different from my proposed solution. In that case I think a simple if/elif/else is the best solution. You could try to use a dict or another iterable with fast contains-lookup.

网友答案:

Maybe this is too simple, but if...elif seems fine to me:

found = False

if 1 in a:
     found = True
elif 2 in a:
     found = True

This only checks if 2 is in the list if 1 isn't, since you're only looking to see if either is in the list (not caring which one), this should be good

Pros:

  • Its simple
  • You can save a check on 2 if 1 is already in the list
  • No need to convert a to a different type (which aides efficiency)

Cons:

  • This won't get you any points for flair

Timing Comparison:

basecase = """
a = [1,2,3,4]
if 1 in a or 2 in a:
    print 'found'
"""

case1 = """
a = [1,2,3,4]
b = [1,2]
if set(b).issubset(set(a)):
    print 'found'
"""

case2 = """
found = False
if 1 in a:
     found = True
elif 2 in a:
     found = True
"""

case3 = """
a = [1,2,3,4]
b = [1,2]
print any(x in a for x in b)
"""

Using print min(timeit.Timer(<case>).repeat(8, 1000)) yields

basecase = 0.0953138421204
case1 = 0.0974782045301
case2 = 0.0958207179797
case3 = 0.068283250742
网友答案:

You can try

if set(a) <= set(b):
    print found

But I can't tell if it's more efficient than your code.

相关阅读:
Top