我正在尝试迭代一个元组列表,同时仍然可以访问前一个元组和下一个元组。具体来说,我需要比较前一个当前元素和下一个元组的y坐标。
这是我用作输入的元组列表:
[(1,1),(2,2),(3,4),(4,3),(5,5),(6,3.5),(7,7),(8,8),(9,9),(10,8),(11,9.5),(11,7.5),(12,12),(13,1.5)]
我最初使用此代码段可以访问上一个,当前和下一个元素:
def previous_and_next(some_iterable):
prevs, current, nexts = tee(some_iterable, 3)
prevs = chain([None], prevs)
nexts = chain(islice(nexts, 1, None), [None])
return zip(prevs, current, nexts)
但我无法使用此函数访问元组的元素,因为它返回有关下标的错误。我对新想法或不同功能持开放态度,因为这显然不是我需要的。
有关更多说明,这是我目前正在尝试实施的功能
UF = UnionFind()
sortedlist = sorted(pointcloud, key=lambda x: x[1])
for previous, current, nxt in previous_and_next(sortedlist):
if previous[1] > current[1] and nxt[1] > current[1]:
UF.insert_objects(current)
elif previous[1] < current[1] and nxt[1] < current[1]:
c=UF.find(previous[1])
d=UF.find(nxt[1])
UF.union(c,d)
else:
c=UF.find(previous[1])
UF.union(current,previous)
return
答案 0 :(得分:1)
与迭代,前一个或下一个元素无关。
真正的问题是你的起点和终点不是const A<U>& rhs
元组。所以这个代码的第一件事就是:
None
因为for previous, current, nxt in previous_and_next(sortedlist):
if previous[1] > current[1] and nxt[1] > current[1]:
UF.insert_objects(current)
为previous
且None
无效(不可订阅)而暂停。
None[1]
所以要么将>>> previous=None
>>> previous[1]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: 'NoneType' object is not subscriptable
替换为由&#34生成的元组;无效&#34;值(如None
,取决于您需要的效果)或过滤掉start&amp;结束三胞胎:
(-1,-1)
答案 1 :(得分:0)
我不确定我理解你的问题,但想想也许这可能会有所帮助:
def previous_and_next(iterable):
iterable = iter(iterable)
prv, cur, nxt = None, next(iterable), next(iterable)
while True:
yield prv, cur, nxt
prv, cur, nxt = cur, nxt, next(iterable)
tuples = [(1, 1), (2, 2), (3, 4), (4, 3), (5, 5), (6, 3.5), (7, 7), (8, 8), (9, 9),
(10, 8), (11, 9.5), (11, 7.5), (12, 12), (13, 1.5)]
for p, c, n in previous_and_next(tuples):
print(p, c, n)
输出:
None (1, 1) (2, 2)
(1, 1) (2, 2) (3, 4)
(2, 2) (3, 4) (4, 3)
(3, 4) (4, 3) (5, 5)
(4, 3) (5, 5) (6, 3.5)
(5, 5) (6, 3.5) (7, 7)
(6, 3.5) (7, 7) (8, 8)
(7, 7) (8, 8) (9, 9)
(8, 8) (9, 9) (10, 8)
(9, 9) (10, 8) (11, 9.5)
(10, 8) (11, 9.5) (11, 7.5)
(11, 9.5) (11, 7.5) (12, 12)
(11, 7.5) (12, 12) (13, 1.5)