简体   繁体   English

元组的元组

[英]Tuple of tuples

I'm new to Python.我是 Python 的新手。 Below code works fine.下面的代码工作正常。

tup1 = ('A', 'B')
tup2 = ('C', 'D')
f = tup1, tup2
for i, j in f:
    print(i,j)

But is there is only one tuple in it.但是里面只有一个元组吗? It will not work.不起作用。 Any reason why?有什么理由吗? Thanks in advance提前致谢

tup1 = ('A', 'B')
f = tup1
for i, j in f:
    print(i,j)

I am expecting result like below.我期待如下结果。 AB AB

f = tup1

Does not create a tuple.不创建元组。 Try this:尝试这个:

f  = (tup1,) # extra comma at the end

Full code:完整代码:

tup1 = ('A', 'B')
f = (tup1,)
for i, j in f:
    print(i,j)

Output: Output:

A B

The code you're writing in only works if there are two items for each index in tup1.您编写的代码仅在 tup1 中的每个索引有两个项目时才有效。 For example, if this were to be the case:例如,如果是这种情况:

    random1 = ('a','b')
    random2 = (3,4)
    tup1 = (random1, random2)
    f = tup1

And then if you used the same loop you had, it would spit out 'a' and 'b' and then 3 and 4. If you're intentions are to just spit out the contents in f, then the following code should do the trick:然后,如果您使用相同的循环,它会吐出“a”和“b”,然后是 3 和 4。如果您只想吐出 f 中的内容,那么下面的代码应该执行诡计:

    tup1 = ('A', 'B')
    f = tup1
    for i in f:
        print(i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM