Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在不展平的情况下迭代一组元组_Python_Python 3.x_Iterator_Tuples - Fatal编程技术网

Python 如何在不展平的情况下迭代一组元组

Python 如何在不展平的情况下迭代一组元组,python,python-3.x,iterator,tuples,Python,Python 3.x,Iterator,Tuples,我想检查一组元组的值。除了检查每个元组的每个值之外,我还需要将一个元组中的最后一个元素与下一个元组中的第一个元素进行比较 我可以迭代一组元组而不将其展平到列表中吗 flattened_tuple = [element for tupl in tupleOfTuples for element in tupl] for i in range(len(flattened_tuple)-1): print(flattened_tuple[i], flattened_tuple[i+1])

我想检查一组元组的值。除了检查每个元组的每个值之外,我还需要将一个元组中的最后一个元素与下一个元组中的第一个元素进行比较

我可以迭代一组元组而不将其展平到列表中吗

flattened_tuple = [element for tupl in tupleOfTuples for element in tupl]

for i in range(len(flattened_tuple)-1):
    print(flattened_tuple[i], flattened_tuple[i+1])
这就是我所想到的,它不会扁平化为一个列表,但我无法将一个元组的最后一个元素与下一个元组的第一个元素进行比较:

   for row in tuple_of_tuples:
    for i, element in enumerate(tuple_of_tuples):
        print(row[i], row[i+1])
对于元组的元组:((0,1,2),(3,4,5),(6,7,8)),我得到以下错误:

0 1
1 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "npuzzle.py", line 67, in goal_test
    print(row[i], row[i+1])
IndexError: tuple index out of range
01
1 2
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
目标测试中第67行的文件“npuzzle.py”
打印(第[i]行,第[i+1]行)
索引器错误:元组索引超出范围

下面的实现建议您迭代成对以允许通过连续元组进行比较

from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

for last, nxt in pairwise(tupleOfTuples):
    if last[-1] == nxt[0]:
        ...

pairwise
实现的优点是可以处理任何类型的iterable,包括生成器等耗材。

首先获取第一个元组的最后一个元素,然后遍历其余元组。根据您的问题,这里有一个可能的解决方案:

last_element = tuple_of_tuples[0][-1]
for row in tuple_of_tuples[1:]:
    first_element = row[0]
    # compare first element to last element
    # ...
    last_element = row[-1]

用于循环的嵌套
?我们需要更多的信息。给我们看一些代码,你尝试了什么?Booo尝试不要命名变量
列表
最大值
最小值
dict
等等-你隐藏了内置函数,并遇到了问题嵌套的for循环会是什么样子?我的嵌套for循环不允许跨子循环比较元素tuples@Matt我错过了那个要求,看看更新的答案。