代码之家  ›  专栏  ›  技术社区  ›  alwayscurious

按差异对元素排序

  •  0
  • alwayscurious  · 技术社区  · 6 年前

    假设我有一张不同年龄的人的名单 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)]

    编辑: 我是说<=从已添加到正确排序列表的上一个年龄开始。 如果把所有年龄在25-45岁的人都包括在内,那就是一组。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Guimoute    6 年前

    我们可以根据你提供的工作。

    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 这很烦人,您还可以编写代码,这样它就会忽略我们最后得到的索引器。不过,这有点不太明确。

    for i,_ in enumerate(people_by_age):
    
        try:      
            ...        
        except IndexError:
            break