排序实际应用场景

汉字、字母排序

from itertools import chain
from pypinyin import pinyin, Style

class sort(object):

    def __init__(self, iter_obj):
        self.iter_obj = iter_obj

    def to_pinyin(self, s):
        return ''.join(chain.from_iterable(pinyin(s, style=Style.TONE3)))

    def is_Chinese(self, ch):
        if '\u4e00' <= ch <= '\u9fff':
                return True
        return False

    def sort_zh_le(self):
        # 分成 字母 和 汉字 两个列表
        letters, chineses = [], []
        for i in self.iter_obj:
            if self.is_Chinese(i[0]):
                chineses.append(i)
            else:
                letters.append(i)
        # 分别排序
        chineses = sorted(chineses, key=self.to_pinyin)
        letters.sort()
        # 合并
        letters.extend(chineses)
        return letters

demo = ['中国', '日本', '美国', 'APPLE', 'apple', '_', 'xiaomi', 'huawei']

target = sort(demo).sort_zh_le()
print(target)

字典排序

demo = {
        'iphone4': '2009',
        'xiaomi': 2017,
        'xsmax': 2018,
        'xs': '2018',
        'oppo': 'findx3pro',
        'vivo': 'x60+plus',
        'xr': '2017',
        'huawei': ['mate40', 'p60pro'],
        'meizu': ['m8'],
        'iwatch7': 2021
        }

from pprint import pprint
pprint(demo.keys())
order_demo = dict(sorted(demo.items(), key=lambda x: x[0], reverse=True))
pprint(order_demo.keys())
posted @ 2021-11-25 14:16  疯狂列表推导式  阅读(67)  评论(0编辑  收藏  举报