zoukankan      html  css  js  c++  java
  • Python函数篇:dict函数和列表生成式

    1.dict函数
    语法:
    dict()

    dict(**kwarg) dict(mapping, **kwarg) dict(iterable, **kwarg)

    第一种:dict()构造一个空字典

    h=dict()
    print(h) #{}

    第二种:dict(**kwargs) dict函数需要传入关键字参数。

    a=dict(one='1',two='2')
    print(a) #{'one': '1', 'two': '2'}

    第三种:dict(mapping,**kwarg)

    b=set([(1,2)])
    print(b) #{(1, 2)}
    b=dict(b)
    print(b) #{1: 2}
    
    c = [(1,'c'), ['c', 1]]
    c=dict(c)
    print(c) #{1: 'c', 'c': 1}
    
    d = ('ac', set('de'))
    print(d)#('ac', {'d', 'e'})
    d=dict(d)
    print(d) #{'a': 'c', 'd': 'e'}

    第四种:高大上了

    e = dict([(['one', 'two'][i - 1], i) for i in (1, 2)])
    print(e) #{'one': 1, 'two': 2}
    
    f = dict({'one': 1, 'two': 2}.items())
    print(f) #{'one': 1, 'two': 2}
    
    g = dict(zip(('one', 'two'), (1, 2)))
    print(g) #{'one': 1, 'two': 2}

    2.列表生成式

    列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建列表的生成式。

    [exp for iter_var in iterable] 
    首先迭代 iterable 里所有内容, 每一次迭代, 都把 iterable 里相应内容放到 iter_var 中, 再在表达式 exp 中应用该 iter_var 的内容, 最后用表达式的计算值生成一个新的列表.

    a=range(1,10)
    >>> [a*a for a in range(1,10)]
    [1, 4, 9, 16, 25, 36, 49, 64, 81]

    可以使用两层循环,可以生成全排列:

    >>> L = [(x, y) for x in range(2) for y in range(3)]
    >>> L
    [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]

    可以使用判断语句

    >>> c = [x for x in range(10) if x > 5]
    >>> c
    [6, 7, 8, 9]

    列表生成式也可以使用两个变量来生成list:

    >>> d = {'a': 'A', 'b': 'B', 'c': 'C' }
    >>> [k + '=' + v for k, v in d.items()]
    ['a=A', 'b=B', 'c=C']

    把一个list中所有的字符串变成小写:

    >>> L = ['I', 'Love', 'Greg']
    >>> [s.lower() for s in L]
    ['i', 'love', 'greg']

    虽然列表生成式好用,但需要只是执行一个循环的时候尽量使用循环而不是列表解析, 这样更符合python提倡的直观性

    当有内建的操作或者类型能够以更直接的方式实现的, 不要使用列表解析. 例如复制一个列表时, 使用 L1=list(L) 即可, 不必使用: L1=[x for x in L]

    如果需要对每个元素都调用并且返回结果时, 应使用 L1=map(f,L), 而不是 L1=[f(x) for x in L].

  • 相关阅读:
    数据结构课后
    idea 使用java 链接sqlservice 2008
    超链接 a href 提交表单通过post方式
    课程主页之课程接口
    课程主页之课程表数据
    课程表分析
    课程前端简单页面
    前台的登录注册
    ORM常用字段及参数与查询 -刘
    Celery配置与使用
  • 原文地址:https://www.cnblogs.com/ningxin18/p/7787452.html
Copyright © 2011-2022 走看看