使用Python循环遍历元组列表

使用Python循环遍历元组列表,python,Python,我有一个元组列表,我试图循环访问每个元组,而不是一次访问所有元组 results = [(1,'one',2,'two'),(3,'three',4,'four')] 到目前为止,我有: for item in (results): for i in (item): print(i) 但这给了我一切,我如何只访问第一个元组,然后分别访问第二个元组?例: 1 one 2 two 然后打破 3 three 4 four 然后继续……迭代列表的第一个元素: for i

我有一个元组列表,我试图循环访问每个元组,而不是一次访问所有元组

results = [(1,'one',2,'two'),(3,'three',4,'four')]
到目前为止,我有:

for item in (results):
    for i in (item):
        print(i)
但这给了我一切,我如何只访问第一个元组,然后分别访问第二个元组?例:

 1
one
2
two
然后打破

3
three
4
four

然后继续……

迭代列表的第一个元素:

for item in results[0]:
        print(item)
for item in results[1]:
        print(item)
输出:

>> python loop.py 
1
one
2
two
>> python loop.py 
3
three
4
four
>> python loop.py 
(1, 'one', 2, 'two')
(3, 'three', 4, 'four')
>> python loop.py 
1
one
2
two
Only between iterations.
3
three
4
four
迭代列表中的第二个元素:

for item in results[0]:
        print(item)
for item in results[1]:
        print(item)
输出:

>> python loop.py 
1
one
2
two
>> python loop.py 
3
three
4
four
>> python loop.py 
(1, 'one', 2, 'two')
(3, 'three', 4, 'four')
>> python loop.py 
1
one
2
two
Only between iterations.
3
three
4
four
仅访问元组:

for item in results:
        print(item)
输出:

>> python loop.py 
1
one
2
two
>> python loop.py 
3
three
4
four
>> python loop.py 
(1, 'one', 2, 'two')
(3, 'three', 4, 'four')
>> python loop.py 
1
one
2
two
Only between iterations.
3
three
4
four
编辑:

迭代两个元组并在它们之间执行某些操作:

counter = 0
for tuple_var in results:
        if counter != 0:
            print("Only between iterations.")
        for element in tuple_var:
            print(element)
        counter += 1 
输出:

>> python loop.py 
1
one
2
two
>> python loop.py 
3
three
4
four
>> python loop.py 
(1, 'one', 2, 'two')
(3, 'three', 4, 'four')
>> python loop.py 
1
one
2
two
Only between iterations.
3
three
4
four

如果这只是为了打印,你可以这样写,如果你想在一行

results=[(1,'1',2,'2'),(3,'3',4,'4')]
打印(*[“{}-{}-{}-{}”。结果中i的格式(*i),sep=“\n下一项\n”)
您可以自己调整格式

*
是一个splat操作符,它解压缩以下列表

“{}-{}-{}-{}”.format(*i)
再次使用splat操作符解压
i
,并通过用
i
中的元素填充每个花括号对其进行格式化

。。。for i in results
是一个for循环理解
i
结果中的每个元组

打印中的
sep
关键字是将在每个项目之间打印的内容。在本例中,在每个元组之间

输出是

1 - one - 2 - two
NEXT ITEM
3 - three - 4 - four

您是否正在查找
结果[0]
?谷歌“如何获取列表的第一个元素”GogoGoAvoid在for循环中的列表周围使用括号,这完全是不必要的。这接近于我试图实现的目标!谢谢我更新了我的问题,使之更具体一点。我更新了我的答案。我希望它能帮助你。如果你有不同的想法,请告诉我。