简体   繁体   English

以两组有效条目检查列表端点的pythonic方法

[英]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" 确保上述代码中“路径”列表的2个端点包含“endpoint1”和“endpoint2”中的元素的最pythonic方法是什么

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. 然后可以实现valid_path的内部结构(John的答案和pillmuncher都是合理的选择),但实际请求有效性检查的代码的读者不需要担心这些细节。

If your aim is to CREATE a list named path verifying the requirement expressed, you can do: 如果您的目标是创建一个名为path的列表来验证表达的需求,您可以:

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 random.sample((endpoint1,endpoint2),2)是得到在随机(端点1,端点2)(端点2,端点1),因此路径[0]端点1是OR在端点2被同时路径[-1]是另一端点名单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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