Python列表 字典操作


Python快速查看列表内重复元素

 前情提要

*在一个长列表内 检查重复的元素 并整合成字典格式
*在输出的时候 保持列表内字典元素排序
列表的排序
字典的排序
列表内字典的排序

列表排序(升序-降序)

测试用例 使用列表的sort

def get_sort(k_list, screen):
    if screen == 1:
        k_list.sort()
        print("升序之后数据:{}".format(k_list))
    elif screen == 2:
        k_list.sort(reverse=True)
        print("降序之后数据:{}".format(k_list))
    else:
        print('参数有误')


list1 = [1, 3, 5, 7, 9, 8, 6, 4, 2]
get_sort(list1, 1)

测试用例 使用 sorted

def get_sort(k_list, screen):
    if screen == 1:
        x = sorted(k_list)
        print("升序之后数据:{}".format(x))
    elif screen == 2:
        x = sorted(k_list, reverse=True)
        print("降序之后数据:{}".format(x))
    else:
        print('参数有误')


list1 = [1, 3, 5, 7, 9, 8, 6, 4, 2]
get_sort(list1, 2)

字典排序(升序-降序)

测试用例 字典排序 根据key value进行排序

def get_sort(k_list, screen):
    if screen == 1:
        x = sorted(k_list.items(), key=lambda x: x[0])
        print("[0]根据 key 升序之后数据:{}".format(x))
    elif screen == 2:
        x = sorted(k_list.items(), key=lambda x: x[1], reverse=True)
        print("[1]根据 value 降序之后数据:{}".format(x))
    else:
        print('参数有误')


k_dict = {'chicken': 3, 'coup': 1, 'info': 2, 'teok': 2, 'for': 1, 'out': 1}
get_sort(k_dict, 2)

列表里面包含字典的 排序(升序-降序)

测试用例 字典排序 根据key value进行排序

import re
from collections import Counter


def get_preposition_isdigit(k_dict):
    preposition = ["of", "with", "at", "from", "into", "during", "including", "until", "against", "among",
                   "throughout", "despite", "towards", "upon", "concerning", "to", "in", "for", "on", "by",
                   "about", "like", "through", "over", "before", "between", "after", "since", "without",
                   "under", "within", "along", "following", "across", "behind", "beyond", "except", "but", "is",
                   "up", "out", "around", "down", "off", "above", "near", "the", "and", "that", "this", "if", "in",
                   "those", "these", "all", "you", "me", "your", "my", "he", "his", "her", "she", "only", 'or', 'it']
    l_list = []
    for k, v in list(k_dict.items()):
        affirm_dict = {}
        if k in preposition or k.isdigit() or re.match(r'^[a-zA-Z]?$', k) or not k.isalpha():
            del k_dict[k]
        else:
            affirm_dict['word'] = k
            affirm_dict['root'] = v
            l_list.append(affirm_dict)
    return l_list


k_list = ['chicken', 'coup', 'chicken', 'info', 'chicken', 'teok', 'info', 'teok', 'for', 'out']

info = get_preposition_isdigit(dict(Counter(k_list)))
data = sorted(info, key=lambda x: x['root'], reverse=True)
print(data)

文章作者: 柒仔
文章链接: /article/12/
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 XiaoLiu!
侵权声明: 若无意对您的文章造成侵权,请您留言,博主看到后会及时处理,谢谢。
评论-----昵称和邮箱必填,网址选填
  目录