我有很多观点。对于每个点,我想画一条与当前点和每个后续点交叉的线。
为了有效地做到这一点,我想确保正确使用Python的迭代器。我考虑过要做这样的事情:
i = 0
for p in points:
head, *tail = points[i::]
pairs = itertools.combinations(head, tail) # this is obviously wrong
for (p1, p2) in pairs:
get_line(p1, p2)
i += 1
但是我在itertools中找不到返回以下方法:(Head,Tail [0]); (头,尾巴[1])...等。
什么是有效的方法?
答案 0 :(得分:2)
听起来您只想迭代组合。像这样的东西将为每对点分配一条线:
from itertools import combinations
points = [1, 2, 3, 4]
def get_line(p1, p2):
print("line", p1, p2)
for pair in combinations(points, 2):
get_line(*pair)
打印:
line 1 2
line 1 3
line 1 4
line 2 3
line 2 4
line 3 4
答案 1 :(得分:0)
import itertools
points = ['p1', 'p2', 'p3', 'p4']
for i, point1 in enumerate(points):
for point2 in itertools.islice(points, i+1, None): # iterator slicing
print(point1, point2)
输出
p1 p2
p1 p3
p1 p4
p2 p3
p2 p4
p3 p4