使用字典键值对列表进行排序

时间:2019-01-21 20:33:48

标签: python python-3.x list sorting

让我说说我有一个列表

def content_gen(url):
    while True:
        res = requests.get("{}/top.htm".format(url), allow_redirects=True)
        soup = BeautifulSoup(res.content, 'html.parser')
        image = "{}/{}".format(
            url,
            soup.html.body.table.find_all('tr')[4].td.table.tr.img['src']
        )
        byte_resp = requests.get(image)
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + byte_resp.content + b'\r\n\r\n')

和命令顺序

list_values = ['key3', 'key0', 'key1', 'key4', 'key2']

如何使用ordered_dict = OrderedDict([('key4', 0), ('key1', 1), ('key2', 2), ('key0', 3), ('key3', 4)]) 键相应地对list_values进行排序?

即:-ordered_dict

编辑:既然几乎所有答案都能解决问题,那么最合适,最完美的pythonic方法是什么?

2 个答案:

答案 0 :(得分:5)

呼叫list.sort,并传递自定义key

list_values.sort(key=ordered_dict.get)    
list_values
# ['key4', 'key1', 'key2', 'key0', 'key3']

或者,非就地版本是使用

完成的
sorted(list_values, key=ordered_dict.get)
# ['key4', 'key1', 'key2', 'key0', 'key3']

答案 1 :(得分:1)

如果我们假设列表是dict的子集:

list_values = ['key3', 'key1']

ordered_dict = OrderedDict([('key4', 0), ('key1', 1), ('key2', 2), ('key0', 3), ('key3', 4)])

output = [v for v in ordered_dict if v in list_values]

print(output)

['key1', 'key3']

示例2:

list_values = ['key3', 'key0', 'key1', 'key4', 'key2']

ordered_dict = OrderedDict([('key4', 0), ('key1', 1), ('key2', 2), ('key0', 3), ('key3', 4)])

output = [v for v in ordered_dict if v in list_values]

print(output)

['key4', 'key1', 'key2', 'key0', 'key3']