zoukankan      html  css  js  c++  java
  • Python的一些小技巧搜集与总结(持续更新)

    一行python实现斐波那契数列:

    fib=lambda n:0 if n<1 else 1 if n<2 else  fib(n-1)+fib(n-2)

    字典排序:

    dic = {'a':3 , 'b':2 , 'c': 1}
    dic1=sorted(dic.iteritems(),key=lambda x:x[0],reverse=True)
    dic2=sorted(dic.iteritems(),key=lambda x:x[1],reverse=False)
    结果:

    dic1=[('c', 1), ('b', 2), ('a', 3)]
    dic2=[('c', 1), ('b', 2), ('a', 3)]

    列表排序:

    >>> x=[(1,'c'),(2,'a'),(3,'b')]
    >>> x
    [(1, 'c'), (2, 'a'), (3, 'b')]
    >>> x.sort()
    >>> x
    [(1, 'c'), (2, 'a'), (3, 'b')]

    >>> x.sort(key=lambda i:i[1])
    >>> x
    [(2, 'a'), (3, 'b'), (1, 'c')]

    将嵌套列表转换成单一列表:

    import itertools

    a = [[1, 2], [3, 4], [5, 6,7]]
    a1=list(itertools.chain.from_iterable(a))

    判断列表中是否有重复元素:

    def Judge(list):
      return len(list)>len(set(list))

    写一个函数, 输入一个字符串, 返回倒序排列的结果:

    def reverse1(string):
      return string[::-1]

    def reverse2(string):
      tgt=list(string)
      for i in range(len(string)):
        tgt[i]=string[len(string)-1-i]
      string=''.join(tgt)
      return string

    合并两列表并排序
    list1 = [2, 3, 8, 4, 9, 5, 6]
    list2 = [5, 6, 10, 17, 11, 2]
    a=sorted(list(set(list1+list2)))

    另外用快排也行

    命名元组

    如果不需要为对象添加行为,并且也预先知道有那些属性需要存储,可以选择使用命名元组,命名元组是只含有属性的元组,对于只读数据是个很好的方式。

    >>> from collections import namedtuple

    >>> Stock = namedtuple('Stock','symbol current high low')
    >>> s1=Stock('GOOG',613,625,610)
    >>> s1.symbol
    'GOOG'

    二维数组转置

    a=[[1,2,3],[4,5,6],[7,8,9]]
    a=[[d[i] for d in a] for i in range(len(a[0]))]
    print(a)

    则a变为[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

  • 相关阅读:
    HDU 1069 Monkey and Banana
    HDU 1029 Ignatius and the Princess IV
    HDU 1024 Max Sum Plus Plus
    Gym100923H Por Costel and the Match
    Codeforces 682C Alyona and the Tree
    Codeforces 449B Jzzhu and Cities
    Codeforces (ccpc-wannafly camp day2) L. Por Costel and the Semipalindromes
    Codeforces 598D (ccpc-wannafly camp day1) Igor In the Museum
    Codeforces 1167c(ccpc wannafly camp day1) News Distribution 并查集模板
    快乐数问题
  • 原文地址:https://www.cnblogs.com/lovealways/p/6774064.html
Copyright © 2011-2022 走看看