美文网首页
数据结构

数据结构

作者: 博楠同学 | 来源:发表于2019-05-09 20:30 被阅读0次
    """
    # 如何在列表 字典 集合中根据条件筛选数据
    """
    
    # 找出data列表中大于0的数字
    from random import randint
    data = [randint(-10, 10) for _ in range(10)]
    result = [i for i in data if i > 0]
    # print(result)
    
    #刷选出data字典中高于90的值
    data = {i: randint(60, 100) for i in range(1, 21)}
    result = {k: v for k, v in data.items() if v > 90}
    # print(data)
    # print(result)
    
    #筛选出data 集合中能被3整除的的值
    data = set(data)
    result = {i for i in data if i % 3 == 0}
    # print(data)
    # print(result)
    
    # 如何为元组中的每个元素命名,提高程序可读性
    # 1、
    NAME, AGE, SEX, MAIL = range(4)
    student = ('aaa', 19, '男', 'aa.@qq.com')
    # print(student[NAME], student[AGE], student[SEX], student[MAIL])
    # 2、
    from collections import namedtuple
    student = namedtuple('student1', ['name', 'age', 'sex', 'mail'])
    s = student('aaa', 19, '男', 'aa.@qq.com')
    # print(s.name, s.age, s.sex, s.mail)
    
    # 如何统计列表中元素出现的频度
    # 1、
    data = [randint(0, 20) for _ in range(30)]
    c = dict.fromkeys(data, 0)
    for i in data:
        c[i] += 1
    print(data)
    print(c)
    # 2、
    from collections import Counter
    c2 = Counter(data)
    print(c2)
    print(c2.most_common(3))
    # 3、词频统计
    import re
    txt = open('.bashrc').read()
    c3 = Counter(re.split('\W+', txt))
    print(c3.most_common(4))
    
    # 根据字典中的值的大小,对字典中的项排序
    # 1、
    data = {x: randint(60, 100) for x in 'abcdefg'}
    # python2
    # data = zip(data.values(), data.keys())
    # python3
    # data = list(zip(data.values(), data.keys()))
    # print(sorted(data))
    
    # 2、
    data = sorted(data.items(), key=lambda x: x[1])
    data = dict(data)
    print(data)
    
    
    # 如何快速找到多个字典中的公共键(key)
    # 1/
    from random import sample
    d1 = {x: randint(1, 4) for x in sample("abcdef", randint(3, 6))}
    d2 = {x: randint(1, 4) for x in sample("abcdef", randint(3, 6))}
    d3 = {x: randint(1, 4) for x in sample("abcdef", randint(3, 6))}
    res = []
    for k in d1:
        if k in d2 and k in d3:
            res.append(k)
    print(d1, d2, d3)
    print(res)
    # 2/
    print(set(d1.keys()) & set(d2.keys()) & set(d3.keys()))
    # 3、
    # def get_key(data):
    #     return set(data.keys())
    # map和reduce的区别,都是把字典或者列表的元素给前面的函数操作,
    #  map一次给一个,  reduce第一次给2个,进行操作后记录下来和后面的在做操作 python3需要引入
    map(lambda v: set(v.keys()), [d1, d2, d3])
    # python3需要引入reduce
    from functools import reduce
    data = reduce(lambda x, y: x & y, map(lambda v: set(v.keys()), [d1, d2, d3]))
    print(data)
    
    
    # 如果让字典保持有序
    
    data = {}
    data['zhang'] = (1, 35)
    data['bo'] = (3, 45)
    data['liang'] = (2, 40)
    
    for v in data:
        print(v)
    print(data)
    
    from collections import OrderedDict
    
    data = OrderedDict()
    data['zhang'] = (1, 35)
    data['bo'] = (3, 45)
    data['liang'] = (2, 40)
    for v in data:
        print(v)
    
    from time import time
    from random import randint
    players = list("ABCDEFgh")
    start = time()
    d = {}
    for i in range(8):
        # input("请输入:")
        p = players.pop(randint(0, 7-i))
        end = time()
        print(i + 1, p, end - start)
        d[p] = (i + 1, end - start)
    
    print(d)
    
    
    print(d.items())
    d = sorted(d.items(), key=lambda v: v[1][1], reverse=True)
    print(dict(d))
    
    # 如何实现用户的历史记录功能
    
    from collections import deque
    history = deque([], 5)
    
    N = randint(0, 100)
    def guess(k):
        if k == N:
            print('right')
            return True
        elif k > N:
            print("%d 比设置值大" % (k,))
            return False
        else:
            print("%d 比设置值小" % (k,))
            return False
    while True:
        line = input("请输入一个数字:")
        if line.isdigit():
            k = int(line)
            history.append(k)
            if guess(k):
                break
        elif line == 'history' or line == 'h?':
            print(list(history))
        elif line == 'exit':
            print("game over")
            break
    
    import pickle
    
    pickle.dump(history, open('history', 'w'))
    p2 = pickle.load(open('history'))
    print(p2)
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:数据结构

          本文链接:https://www.haomeiwen.com/subject/iwggoqtx.html