简体   繁体   English

为什么我不能从列表中打印单个元组?

[英]why can't I print a single tuple from a list?

I'm just trying to flip and print the first tuple in a list. 我只是试图在列表中翻转和打印第一个元组。 If I try this code I get error "cannot unpack non-iterable int object" 如果我尝试这个代码我得到错误“无法解压缩不可迭代的int对象”

lst = [('a',1),('b',2),('c',3)]
for x,y in lst[0]:
    print(y,x)

However if I make this simple edit, it works fine. 但是,如果我进行这个简单的编辑,它可以正常工作。 why can't I print a single tuple from a list? 为什么我不能从列表中打印单个元组?

lst = [('a',1),('b',2),('c',3)]
for x,y in lst[:1]:
    print(y,x)

Your list: 你的清单:

lst = [('a',1),('b',2),('c',3)]

The first element of the list: 列表的第一个元素:

>>> lst[0]
(1, 'a')

Then when you iterate over this, you are asking to unpack each element . 然后当你迭代这个时,你要求解压每个元素 It would be like writing 这就像写作

for x, y in 1:
    # do something
for x, y in 'a':
    # do something

Wth lst[:1] , you are slicing the list, and getting a list of tuples back. Wth lst[:1] ,你正在切割列表,并获得一个元组列表。

Easiest way to flip first element would be to: 翻转第一个元素的最简单方法是:

lst = [('a',1),('b',2),('c',3)]
print((lst[0][1], lst[0][0])) # -> (1, 'a')

However reason why your code throws error here is because you try to iterate over element instead of list, where element is ('a',1) by iterating over it first value is 'a' and you try to split it into 2 variables x and y which throws an error. 然而,你的代码抛出错误的原因是因为你尝试迭代元素而不是列表,其中元素是('a',1)通过迭代它,第一个值是'a' ,你试图将它分成2个变量xy抛出错误。

print(type(lst[0])) # -> <class 'tuple'>
for x,y in lst[0]:
    print(y,x)

Here if we iterate over list [('a',1)] (because we used slice as list index instead of integer) first value is indeed ('a',1) and we can split it into x and y variables without errors. 这里如果我们迭代list [('a',1)] (因为我们使用slice作为列表索引而不是整数),第一个值确实是('a',1) ,我们可以将它分成xy变量而不会出错。

print(type(lst[:1])) # -> <class 'list'>
for x,y in lst[:1]:
    print(y,x)

You are trying to loop through the first element of the list. 您正在尝试遍历列表的第一个元素。 Just unzip the first element and print: 只需解压缩第一个元素并打印:

x, y = lst[0]
print(y,x)

or in a loop: 或循环:

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

You don't want a loop there. 你不想在那里循环。 lst[0] is the tuple you want to flip, there is no need to iterate. lst[0]是你要翻转的元组,没有必要迭代。

x, y = lst[0]
print(y, X)

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

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