美文网首页Python
可能会用的pyhton小知识点

可能会用的pyhton小知识点

作者: 随心录 | 来源:发表于2017-12-27 10:17 被阅读28次

    交换值

    >>> a = 1
    >>> b = 2
    >>> a , b = b , a
    >>> a
    2
    >>> b
    1
    

    列表解包

    >>> a, b, c = [1, 2, 3]
    >>> a
    1
    >>> b 
    2
    >>> c
    3
    >>> a, *other = [1, 2, 3]
    >>> a
    1
    >>> other
    [2, 3]
    

    扩展列表

    >>> i = ['a', 'b', 'c']
    >>> i.extend(['e', 'f', 'g'])
    >>> i
    ['a', 'b', 'c', 'e', 'f', 'g']
    

    列表负数索引

    >>> a = [1,2,3]
    >>> a[-1]
    3
    

    列表切片

    >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> a[3:6] # 第3个到第6个之间的元素
    [3, 4, 5]
    >>> a[:5] # 前5个元素
    [0, 1, 2, 3, 4]
    >>> a[5:] # 后5个元素
    [5, 6, 7, 8, 9]
    >>> a[::] # 所有元素(拷贝列表)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> a[::2] # 偶数项
    [0, 2, 4, 6, 8]
    >>> a[1::2] # 奇数项
    [1, 3, 5, 7, 9]
    >>> a[::-1] # 反转列表
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    

    二维数组变一维数组

    import itertools
    >>> a = [[1, 2], [3, 4], [5, 6]]
    >>> i = itertools.chain(*a)
    >>> list(i)
    [1, 2, 3, 4, 5, 6]
    

    有索引的迭代

    >>> a = ['Merry','Christmas','Day']
    >>> for i, x in enumerate(a):
     ...    print('{}: {}'.format(i,x))
     ...
     0: Merry
     1: Christmas
     2: Day
    

    列表推导式

    >>> le = [x * 2 for x in range(10)]
    >>> le # 每个数取2倍
    [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
    
    >>> le = [x for x in range(10) if x % 2 == 0]
    >>> le # 获取偶数项
    [0, 2, 4, 6, 8]
    

    生成器表达式

    >>> ge = (x * 2 for x in range(10))
    >>> ge
    <generator object <genexpr> at 0x01948A50>
    >>> next(ge)
    0
    >>> next(ge)
    4
    ...
    >>> next(ge)
    Traceback(most recent call last):
      File "<stdin>",line 1, in <module>
    StopInteration
    

    集合推导式

    >>> nums = {n ** 2 for n in range(10)}
    >>> nums
    {0, 1, 64, 4, 36, 9, 16, 49, 81, 25}
    

    字典推导式

    >>> d = {s : len(s) for s in ["one", "two", "three"]}
    >>> d
    {'one': 3, 'two': 3, 'three': 5}
    

    合并两个字典

    >>> def merge_dicts(d1,d2):
            return {k: v for d in (d1,d2) for k, v in d.items()}
    >>> merge_dicts({"1":"2"}, {"a":"b"})
    {'1':'2', 'a':'b'}
    

    字符串合并

    >>> i = ['a', 'b', 'c']
    >>> "".join(i)
    'abc'
    

    判断key是否存在字典中

    >>> d = {"1":"a"}
    >>> d['2']
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: '2'
    >>> '1' in d
    True
    >>> d['1']
    'a'
    >>> d.get("1")
    'a'
    >>> d.get("2")
    >>>
    

    三元运算

    >>> d = {'1','a'}
    >>> exist = True if '2' in d else False
    >>> exist
    False
    

    装饰器

    from functools import wraps 
    
    def tags(tag_name):
      def tags_decorator(func):
        @wraps(func)
        def func_wrapper(name):
          return "<{0}>{1}</{0}>".format(tag_name,func(naem))
        return func_wrapper
      
    @tags("p")
    def get_text(name):
      """returns some text"""
      return "Hello " + name
    
    print(get_text("Python"))
    >>> <p>Hello Python</p>
    

    字典子集

    >>> def sub_dicts(d, keys):
     ...    return {k:v for k, v in d.items() if k in keys}
     ...
    >>> sub_dicts({1:'a', 2:'b', 3:'c'},[1, 2])
    {1:'a', 2:'b'}
    

    两个列表转换字典

    >>> a = [1, 2, 3]
    >>> b = ['a', 'b', 'c']
    >>> dict(zip(a,b))
    {1:'a', 2:'b', 3:'c'}
    

    反转字典

    >>> d = {'a':1, 'b':2, 'c':3, 'b':4}
    >>> zip(d.values(), d.keys())
    <zip object at 0x019136E8>
    >>> z = zip(d.values(), d.keys())
    >>> dict(z)
    {1:'a', 2:'b', 3:'c', 4:'d'}
    

    具名元组

    >>> from collectons import namedtuple
    >>> Point = namedtuple("Point", "x,y")
    >>> p = Point(x = 1, y =2)
    >>> p.x
    1
    >>> p[0]
    1
    >>> p.y
    2
    >>> p[1]
    2
    

    默认字典

    >>> from collections import defaultdict
    >>> d = defaultdict(list)
    >>> d["a"]
    []
    >>> d["a"].append(1)
    >>> d["a"]
    [1]
    
    >>> d = defaultdict(lambda: [1])
    >>> d
    defaultdict(<function <lambda> at 0x00c0DB28>, {})
    >>> d['a']
    [1]
    

    设置字典的默认值

    >>> d = dict()
    >>> if 'a' not in d:
     ...    d['a'] = []
     ...
    >>> d['a'].append(1)
    >>> d
    {'a': [1]}
    
    >>> d.setdefault('b',[]).append(2)
    >>> d
    {'a':[1], 'b':[2]}
    

    频数统计

    >>> from collections import Counter
    >>> import random
    >>> a = [random.randint(0,10) for __ in range(20)]
    >>> a
    [5, 4, 9, 6, 4, 2, 4, 6, 9, 5, 5, 1, 3, 6, 9, 1, 6, 1, 5, 5]
    >>> Counter(a)
    Counter({5: 5, 6: 4, 1: 3, 4: 3, 9: 3, 2: 1, 3: 1})
    

    有序字典

    >>> d = dict((str(x), x) for x in range(10))
    >>> d.keys() # key 无序
    dict_keys(['8', '2', '6', '9', '1', '0', '5', '4', '7', '3'])
    
    >>> from collections import OrderedDict
    >>> m  = OrderedDict((str(x), x) for x in range(10))
    >>> m.keys() # key 按照插入的顺序排列
    odict_keys(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
    

    列表中最大最小的前n个数

    >>> import heapq
    a = [51, 95, 14, 65, 86, 35, 85, 32, 8, 98]
    >>> heapq.nlargest(5,a)
    [98, 95, 86, 85, 65]
    >>> heapq.nsmallest(5, a)
    [8, 14, 32, 35, 51]
    

    for ... else

    found = False
    for i in foo:
        if i == 0:
            found = True
            break
    if not found:
        print("i was never 0")
        
    
    for i in foo:
        if i == 0:
            break
    else:
        print("i was never 0")
    
    

    打开文件

    >>> with open('foo.txt', 'w') as f:
    ...     f.write("hello")
    

    相关文章

      网友评论

        本文标题:可能会用的pyhton小知识点

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