Python 如何进行元组排序
输出:Python 如何进行元组排序,python,sorting,tuples,Python,Sorting,Tuples,输出: Enter your name, age & score: a 17 99 Enter your name, age & score: a 19 98 Enter your name, age & score: a 19 100 Enter your name, age & score: a 19 99 Enter your name, age & score: b 19 99 Enter your name, age & sco
Enter your name, age & score: a 17 99
Enter your name, age & score: a 19 98
Enter your name, age & score: a 19 100
Enter your name, age & score: a 19 99
Enter your name, age & score: b 19 99
Enter your name, age & score: b 19 98
Enter your name, age & score: b 19 100
Enter your name, age & score: -1
输出应如下所示:
(‘a’、‘17’、‘99’、‘a’、‘19’、‘98’、‘a’、‘19’、‘99’、‘a’、‘19’、‘100’、‘b’、‘19’、‘98’、‘b’、‘19’、‘99’、‘b’、‘19’、‘100’)
我该怎么做?这是我的密码
(('a', '17', '99'), ('a', '19', '100'), ('a', '19', '98'), ('a', '19', '99'), ('b', '19', '100'), ('b', '19', '98'), ('b', '19', '99'))
元组排序正确,因为它们只包含字符串。如果要进行数字排序,请将值存储为整数:
def check(txt):
global c
if txt.count(" ") == 2:
tup=(tuple(txt.split(" ")))
list1.append(tup)
list1.sort()
else:
if txt != "-1":
c= 1
return c
main() # prints the converted list to tuple..
试一试
我不清楚您是如何尝试对它们进行排序的。获取输出的规则是什么?你的输出对我来说没有任何意义。很抱歉,我已经在那里编辑了错误。应该是98 99 100我试过了,成功了。但是我不太明白它是如何工作的。hahasorted将使用一个
键
==>指定一个参数的函数,该参数用于从每个列表元素中提取一个比较键
。在此之前,请将每个元素中的第2项和第3项的键转换为int。首先,您是否了解原始输出为何如此?@KarlKnechtel我想是的
parts = txt.split(" ")
list1.append(tuple(parts[0], int(parts[1]), int(parts[2]))
sorted(your_tup, key=lambda x: [x[0], int(x[1]), int(x[2])])