在 Python3 中解包 iterables?
Unpacking iterables in 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
循环时,它打印出元组:
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')
[]
所以,元组就在那里。他们为什么不自己打开包装?
您的第二个 for 循环正在遍历元组中的项目,但您同时获取了其中的两个项目。我想这就是你想要的:
# 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))
为什么要返回 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
循环时,它打印出元组:
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')
[]
所以,元组就在那里。他们为什么不自己打开包装?
您的第二个 for 循环正在遍历元组中的项目,但您同时获取了其中的两个项目。我想这就是你想要的:
# 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))