Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何进行元组排序_Python_Sorting_Tuples - Fatal编程技术网

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])])