简体   繁体   中英

pythonic way of checking endpoints of a list against two sets of valid entries


endpoint1 = [1,2,3]
endpoint2 = [4,5,6]
path = list(random.randrange(0,9) for x in range(10))

What's the most pythonic way to make sure the 2 endpoints of the "path" list in the above code contains an element in both "endpoint1" and "endpoint2"

Something like this, but prettier:


if path[0] in endpoint1:
    if path[-1] in endpoint2:
        print "valid"

if path[0] in endpoint2:
    if path[-1] in endpoint1:
        print "valid"



Well you can do the whole thing in one expression.

if path[0] in endpoint1 and path[-1] in endpoint2 or \
   path[0] in endpoint2 and path[-1] in endpoint1:

I don't think it'll get much better than that.

If the valid endpoints are only a few and you want to test many paths then generating all possible pairs of end points upfront might not be too costly:

import itertools

valid_endpoints = set(itertools.product([1, 2, 3], [4, 5, 6]))
valid_endpoints.update([(b, a) for (a, b) in valid_endpoints])

many_paths = ... # get many paths from somewhere

for path in many_paths:
    if (path[0], path[-1]) in valid_endpoints:
        print 'valid!'

Depending on how many different places you perform this check, the clearest way would likely to be to create a function to be used as follows:

if valid_path(path):
    print "valid"

The internals of valid_path can then be implemented however you like (both John's answer and pillmuncher's would be reasonable choices), but readers of the code actually requesting the validity checks won't need to worry about those details.

If your aim is to CREATE a list named path verifying the requirement expressed, you can do:

endpoint1 = [1,2,3]
endpoint2 = [4,5,6]
path = map(random.choice, random.sample((endpoint1,endpoint2),2))
path[1:1] = list(random.randrange(0,9) for x in range(8))

random.sample((endpoint1,endpoint2),2) is to obtain at random (endpoint1,endpoint2) or (endpoint2,endpoint1) hence path[0] being in endpoint1 OR being in endpoint2 while path[-1] is the other endpoint list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM