本文介绍了在Python3中解包可迭代对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么返回in sort_tup_from_list for key, val in tup: ValueError: not enough values to unpack (expected 2, got 1)
# list with tuples
lst = [("1", "2"), ("3", "4")]
# sorting list by tuple val key
def sort_tup_from_list(input_list):
tmp = []
print(tup)
for tup in input_list:
for key, val in tup:
tmp.append((val, key))
tmp.sort(reverse=True)
return tmp
print(sort_tup_from_list(lst))
当我注释掉第二个for
循环时,它会打印出元组:
When I comment out second for
loop, it prints tuple:
lst = [("1", "2"), ("3", "4")]
def sort_tup_from_list(input_list):
tmp = []
for tup in input_list:
print(tup)
# for key, val in tup:
# tmp.append((val, key))
# tmp.sort(reverse=True)
return tmp
print(sort_tup_from_list(lst))
输出:
('1', '2')
('3', '4')
[]
因此,元组在那里.他们为什么不给自己拆包?
So, tuples are there. Why are they not unpacking themselfs?
推荐答案
您的第二个for循环正在遍历元组中的项目,但是您正在抓取其中的两个项目.我想这就是你想要的:
Your second for loop is looping through items in the tuple, but you're grabbing both of the items in it. I think this is what you want:
# list with tuples
lst = [("1", "2"), ("3", "4")]
# sorting list by tuple val key
def sort_tup_from_list(input_list):
tmp = []
print(tmp)
for key,val in input_list:
tmp.append((val, key))
tmp.sort(reverse=True)
return tmp
print(sort_tup_from_list(lst))
这篇关于在Python3中解包可迭代对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!