zoukankan      html  css  js  c++  java
  • 构造字典

    有一个列表values=[1,3,5,7,9,12,56,98,23,77,67,87,99,4,3,43,54,23],请构造一个字典,当值小于50时key为small,当值大于等于50时key为big。

    方法一:

    dic = {}   #定义一个空的字典
    values=[1,3,5,7,9,12,56,98,23,77,67,87,99,4,3,43,54,23]
    for i in values: #对字典进行遍历
    if i < 50 :
    if 'small' in dic.keys(): #判断small这个key是否在字典中
    dic['small'].append(i)
    else:
    dic['small']=[i]
    else:
    if 'big' in dic.keys():
    dic['big'].append(i)
    else:
    dic['big']=[i]
    print("The new dictionary is %s" % dic)

    The new dictionary is {'small': [1, 3, 5, 7, 9, 12, 23, 4, 3, 43, 23], 'big': [56, 98, 77, 67, 87, 99, 54]}

    方法二:

    import collections
    dic = collections.defaultdict(list) #定义一个字典,默认是列表
    values=[1,3,5,7,9,12,56,98,23,77,67,87,99,4,3,43,54,23]
    for i in values:
    if i < 50:
    dic['small'].append(i)
    else:
    dic['big'].append(i)
    print("The new dictionary is %s" % dic)

    The new dictionary is defaultdict(<class 'list'>, {'small': [1, 3, 5, 7, 9, 12, 23, 4, 3, 43, 23], 'big': [56, 98, 77, 67, 87, 99, 54]})

    以上两种方法仅供参考,有需要的朋友可以看一下,共同探讨共同进步。

    QQ:1127000483

  • 相关阅读:
    十九:数字排重
    十八:十六进制转八进制
    Dubbo Notes
    Concurrent Package
    MySQL(8.0)官方文档阅读笔记
    MyBatis笔记
    分布式事务
    RabbitMQ笔记
    Kafka官方文档阅读笔记
    Cassandra Note
  • 原文地址:https://www.cnblogs.com/winter1519/p/7019914.html
Copyright © 2011-2022 走看看