首页 > for..in..如何将列表中的元组整个迭代出来?

for..in..如何将列表中的元组整个迭代出来?

定义一个列表:

r=[(1,2),('a','f')]

想用 for..in.. 迭代来获取元组。

于是用了下面方法:

r = [(1,2), ('a','f')]

for x,y in r:
    print(x,y)

然而,输出的结果是:

1  2
'a'  'f'

我想要迭代出的是整个元组,这样的效果:

(1,2)(‘a’,‘f’)

该如何去做?


直接迭代 tuple 而不要去做 unpacking:

r = [(1,2), ('a','f')]

for t in r:
    print(t)

因應你在評論下的問題,如果 r 中有非 tuple 的東西,可以用 generator expression 並搭配 isinstance 的檢查來完成:

r = [(1,2), 5, ('a','f')]
tuples = (t for t in r if isinstance(t, tuple))

for t in tuples:
    print(t)

甚至你也可以檢查是否為雙元素的 tuple:

r = [(1,2), 5, ('a','f')]
tuples = (t for t in r if isinstance(t, tuple) and len(t)==2)

for t in tuples:
    print(t)

使用Python版本 3.4.4:

# -*- coding:utf-8 -*-

tuple = [(1,2,3),('1','5',9.0)]

for t in tuple:
          print ("带括号的输出",t)

for a,b,c in tuple:
          print ("不带括号的输出",a,b,c)
运行结果:
带括号的输出 (1, 2, 3)
带括号的输出 ('1', '5', 9.0)
不带括号的输出 1 2 3
不带括号的输出 1 5 9.0

To get the whole tuple, you just need:

for t in l:
    print t
【热门文章】
【热门文章】