简体   繁体   English

打包多个python元组并排序

[英]pack multiple python tuple and sort

Question: You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers.问题:您需要编写一个程序来按升序对 (name, age, height) 元组进行排序,其中 name 是字符串,age 和 height 是数字。 The tuples are input by console.元组由控制台输入。 The sort criteria is:排序标准是:

1: Sort based on name; 1:按名称排序; 2: Then sort based on age; 2:然后根据年龄排序; 3: Then sort by score. 3:然后按分数排序。 The priority is that name > age > score.优先级是姓名>年龄>分数。 If the following tuples are given as input to the program: Tom,19,80 John,20,90 Jony,17,91 Jony,17,93 Json,21,85 Then, the output of the program should be: [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]如果将以下元组作为程序的输入给出: Tom,19,80 John,20,90 Jony,17,91 Jony,17,93 Json,21,85那么程序的输出应该是: [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]

My code:我的代码:

info = input()
info_list = [(name, age, height) for name, age, height in 
case.split(',') for case in info.split(' ')] 
sorted(info_list, key = lambda name:name[0])

The error I got was: ValueError: too many values to unpack (expected 3)我得到的错误是: ValueError: too many values to unpack (expected 3)

Can anyone please help?有人可以帮忙吗?

The solution would be:解决方案是:

info = input()
info_list = [case.split(',') for case in info.split(' ')] 
print(sorted(info_list))

Example output:示例输出:

Tom,19,80 John,20,90 Jony,17,91 Jony,17,93 Json,21,85
[['John', '20', '90'], ['Jony', '17', '91'], ['Jony', '17', '93'], ['Json', '21', '85'], ['Tom', '19', '80']]

And to explain why your code doesn't work is:并解释为什么您的代码不起作用是:

  • Using multiple iterators, only works for a sequence of sequences, whereas just one sequence won't work.使用多个迭代器,仅适用于一系列序列,而只有一个序列不起作用。

  • Why doesn't it work with a sequence, it will try to unpack the singular element, ie 1 , which can't be unpacked as it isn't an iterable with 3 elements, that's the main reason it works for ie [1, 2, 3] .为什么它不适用于序列,它会尝试解包单个元素,即1 ,因为它不是具有 3 个元素的可迭代元素,所以无法解包,这是它适用于即[1, 2, 3]

Use key to sorted to specify the base of your sort.使用key to sorted指定排序的基础。

s = 'Tom,19,80 John,20,90 Jony,17,91 Jony,17,93 Json,21,85'

lst = [tuple(x.split(',')) for x in s.split()]

print(sorted(lst, key=lambda x: (x[0], x[1], x[2])))
# [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]                                      [Program finished]

where s is your input string.其中s是您的输入字符串。

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

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