[英]How to sort a list alphabetically and have additional lists sorted in the same order
I have 3 lists, each with equal elements: email addresses, salaries and IDs 我有3个列表,每个列表具有相同的元素:电子邮件地址,薪水和ID
I'd like to sort the email addresses alphabetically and in some way sort the other 2 lists (salaries and IDs). 我想按字母顺序对电子邮件地址进行排序,并以某种方式对其他两个列表(薪水和ID)进行排序。
E.g.,
Emails:
z@company.com
a@company.com
Salaries:
50000
60000
IDs:
2
1
The puzzle: I'd like to sort Emails such that a@c.com is first and z@c.com is last and Salaries is 60000 then 50000 and IDs is 1 then 2. 难题:我想对电子邮件进行排序,使得a@c.com在前,z @ c.com在后,薪水是60000,然后是50000,ID是1,然后是2。
Additional detail: 其他细节:
1. Length of lists are the same and can be longer than two elements. 1.列表的长度相同,并且可以大于两个元素。
2. I will subsequently pass IDs to functions to retrieve further lists. 2.随后,我将ID传递给函数以检索更多列表。 Those lists won't need sorting as they will adopt the order of the IDs list.
这些列表将不需要排序,因为它们将采用 ID列表的顺序。
Try: 尝试:
emails = ["z@c.com", "a@c.com"]
salaries = [50, 60]
ids = [2, 1]
intermediate = zip(emails, salaries, ids)
intermediate.sort()
result = zip(*intermediate)
This is essentially ebo's solution, made to a one-liner with the user of sorted() rather than list.sort, and multiple lvalues in the assignement to get the individual list (named as the original but with an s_
prefix) directly. 本质上,这是ebo的解决方案,使用sorted()而不是list.sort的用户实现单线,并且在分配中使用多个左值直接获取单个列表(命名为原始列表,但带有
s_
前缀)。
>>> email = ['z@company.com', 'a@company.com']
>>> salaries = [50000, 60000]
>>> ids = [2,1]
>>> s_email, s_salaries, s_ids = zip(*sorted(zip(email, salaries, ids)))
>>> s_email
('a@company.com', 'z@company.com')
>>> s_salaries
(60000, 50000)
>>> s_ids
(1, 2)
>>>
Assuming that each email ID is unique, then this will work: 假设每个电子邮件ID是唯一的,那么它将起作用:
sortedEmails = emails[:]
sortedEmails.sort()
sortedSalaries = []
for email in sortedEmails:
i = emails.index(email)
sortedSalaries.append(salaries[i])
Hope that helps 希望能有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.