zoukankan      html  css  js  c++  java
  • python字典元组和集合

    字典的内置函数

    1.sorted 排序,让字典的数据按照顺序输出

    found = {'a':0,'u':2,'i':0}
    
    for keys in found:
        print(keys)   #a u i
    
    
    for keys in sorted(found):
        print(keys)    # a i u

    2.items,返回一个键值对列表

    found = {'a':0,'u':2,'i':0}
    
    for keys in found:
        print(keys)   #a u i
    
    for keys,values in found.items():
        print("keys = {} and values ={}".format(keys,values))
        # keys = a and values =0
        # keys = u and values =2
        # keys = i and values =0
    
    for keys,values in sorted(found.items()):
        print("keys = {} and values ={}".format(keys,values))
        # keys = a and values =0
        # keys = i and values =0
        # keys = u and values =2

    3.字典初始化函数 setdefault

    fruits = ['apples','bananas','pears']
    found = {'apples':2,'pears':3}
    
    for fruit in fruits:
        if fruit in found:
            found[fruit] += 1
        else:
            found[fruit] = 1
        print('{}个数为{}'.format(fruit,found[fruit]))
    
    
    # 等价于:
    for fruit in fruits:
        found.setdefault(fruit,0)
        found[fruit] += 1
        print('{}个数为{}'.format(fruit,found[fruit]))

    集合

    特性:不重复,无序

    1.union合并集合,将集合A和B合并,去重后创建一个新集合

    vowels = set('aeiou')
    
    print(vowels)  #{'i', 'a', 'u', 'o', 'e'}
    
    word = 'hello'
    
    u = vowels.union(set(word))   #{'o', 'i', 'u', 'e', 'h', 'a', 'l'}

    2.difference,给定两个集合,告诉你哪些元素只在集合A中存在而不在集合B中存在

    vowels = set('aeiou')
    
    print(vowels)  #{'i', 'a', 'u', 'o', 'e'}
    
    word = 'hello'
    
    l = vowels.difference(set(word))    #{'u', 'a', 'i'}

    3.intersection报告共同元素,即集合A和集合B的共同元素

    vowels = set('aeiou')
    
    print(vowels)  #{'i', 'a', 'u', 'o', 'e'}
    
    word = 'hello'
    
    i = vowels.intersection(set(word))   #{'o', 'e'}

    元祖

    特性:不可变

    优势:提供性能,避免不必要的开销

    创建规则:特例

    只有一个对象的元祖,创建时需要在末尾加上,

    t = ('python')
    print(type(t))   #<class 'str'>
    print(t)    #python
    
    s = ('python',)
    print(type(s))    #<class 'tuple'>
    print(s)    #('python',)
  • 相关阅读:
    问题及解决:使用dotnet publish发布时Visual Stuido创建的配置文件中的路径失效
    模式的定义
    Identity Server 4 从入门到落地(三)—— 创建Web客户端
    信息系统的不能和能
    虚拟机中CentOS 6.8 Linux搭建GitLab服务器(安装篇)
    Eclipse快捷键大全
    冒泡排序实现
    JAVA的数据类型
    IDEA快捷键大全(翻译自官方手册)
    IntelliJ IDEA入门设置指南
  • 原文地址:https://www.cnblogs.com/like1824/p/14642240.html
Copyright © 2011-2022 走看看