迭代python中的嵌套元组(iterating through a nested tuple in python)

编程入门 行业动态 更新时间:2024-10-23 11:34:05
迭代python中的嵌套元组(iterating through a nested tuple in python)

我是python的新手,并试图弄清楚如何迭代嵌套元组。

这是一个元组:

x=((1,2,('a', 'b', (6,9,7)), 6,('$','@')))

我正在尝试迭代,所以我可以分别打印每个值,如:

1 2 a b 6 9 7 6 $ @

这是我的代码,请让我知道我在这里做错了什么:

x=((1,2,('a', 'b', (6,9,7)), 6,('$','@'))) f=0 for y in x: print(x[f]) f = f+1

I'm new to python and trying to figure out how to iterate through a nested tuple.

here is a tuple:

x=((1,2,('a', 'b', (6,9,7)), 6,('$','@')))

I'm trying to iterate so I can print each value separately like:

1 2 a b 6 9 7 6 $ @

Here is my code, please let me know what I'm doing wrong here:

x=((1,2,('a', 'b', (6,9,7)), 6,('$','@'))) f=0 for y in x: print(x[f]) f = f+1

最满意答案

你可以试试递归。 检查元素是否为元组,如果是,则进行递归调用,如果不是则打印它。

x=(((1,2,3,4),2,('a', 'b', (6,9,7)), 6,('$','@'))) def foo(a): for b in a: if isinstance(b,tuple): foo(b) else: print b foo(x)

输出:

1 2 3 4 2 a b 6 9 7 6 $ @

You can try with recursion. Check if element is tuple, if it is then make a recursive call to function, if it is not then print it.

x=(((1,2,3,4),2,('a', 'b', (6,9,7)), 6,('$','@'))) def foo(a): for b in a: if isinstance(b,tuple): foo(b) else: print b foo(x)

Output:

1 2 3 4 2 a b 6 9 7 6 $ @

更多推荐

本文发布于:2023-08-07 19:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465991.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   迭代   python   tuple   iterating

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!