说我有一个年龄int
和收入int
不同的人的列表,我想按以下顺序对他们进行排序:
people = [(25, 10000), (45, 22000), (20, 11000), (26, 13000), (27, 11000)]
people_new = [(20, 11000), (25, 10000), (27, 11000), (26, 13000), (45, 22000)]
首先按年龄排序。 其次,将年龄最接近的人(即每个人之间的年龄差异<= 2)按收入顺序排列。只要年龄之间彼此接近,年龄就没那么重要了。
可以使用列表上的sorted
函数来完成此操作吗?
如果我写:
people_new = sorted(people, key = lambda t: (t[0],t[1]))
27岁的人身体不好,所以这是不正确的。
[(20,11000),(25,10000),(26,13000),(27,11000),(45,22000)]
我需要编写一个新函数吗?如果是这样,是否有一种简短的pythonic方法?
编辑: 年龄是 close ,我的意思是说<= 2,它是添加到正确排序列表中的上一个年龄。 因此可以添加20岁年龄段,但是由于没有21岁或22岁,因此25岁成为下一组的起点,并且将查看25、26岁,27岁...。 如果包括所有25-45岁的年龄段,那将是一组。
答案 0 :(得分:1)
我们可以根据您提供的信息进行工作。
people = [(25, 10000), (45, 22000), (20, 11000), (26, 13000), (27, 11000)]
people_by_age = sorted(people, key = lambda t: (t[0], t[1]))
# [(20, 11000), (25, 10000), (26, 13000), (27, 11000), (45, 22000)]
N = len(people_by_age)
for i,_ in enumerate(people_by_age):
# For all but the last person.
if i+1 < N:
# If the current and next persons have a close age.
if abs(people_by_age[i][0] - people_by_age[i+1][0]) <= 2:
# Swap their position in the list based on income.
if people_by_age[i][1] < people_by_age[i+1][1]:
temp = people_by_age[i]
people_by_age[i] = people_by_age[i+1]
people_by_age[i+1] = temp
print(people_by_age) # by age and income.
# [(20, 11000), (26, 13000), (27, 11000), (25, 10000), (45, 22000)]
如果您认为添加i+1<N
很烦人,则还可以编写代码,使其忽略我们最后将得到的IndexError。不过,它不够明确。
for i,_ in enumerate(people_by_age):
try:
...
except IndexError:
break