`

Python中你不知道的特性

阅读更多

无穷嵌套的列表

 

>>> a = [1, 2, 3, 4] 
>>> a.append(a) 
>>> a 
[1, 2, 3, 4, [...]] 
>>> a[4] 
[1, 2, 3, 4, [...]] 
>>> a[4][4][4][4][4][4][4][4][4][4] == a 
True

 

无穷嵌套的字典

>>> a = {} 
>>> b = {} 
>>> a['b'] = b 
>>> b['a'] = a 
>>> print a 
{'b': {'a': {...}}}

 

列表重构

>>> l = [[1, 2, 3], [4, 5], [6], [7, 8, 9]] 
>>> sum(l, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

或者

import itertools 
data = [[1, 2, 3], [4, 5, 6]] 
list(itertools.chain.from_iterable(data))

再或者

from functools import reduce
from operator import add
data = [[1, 2, 3], [4, 5, 6]]
reduce(add, data)

 

 

字典生成

>>> {a:a**2 for a in range(1, 10)}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

 

类中方法重置

class foo:
   def normal_call(self):
       print("normal_call")
   def call(self):
       print("first_call")
       self.call = self.normal_call


>>> y = foo()
>>> y.call()
first_call
>>> y.call()
normal_call
>>> y.call()
normal_call

获取类属性
class GetAttr(object):
   def __getattribute__(self, name):
       f = lambda: "Hello {}".format(name)        return f
>>> g = GetAttr()
>>> g.Mark()
'Hello Mark'

集合
>>> a = set([1,2,3,4])
>>> b = set([3,4,5,6])
>>> a | b # Combining{1, 2, 3, 4, 5, 6}
>>> a & b # Intersection{3, 4}
>>> a < b # SubsetsFalse>>> a - b # Variance{1, 2}
>>> a ^ b # The symmetric difference{1, 2, 5, 6}

集合定义必须使用set关键字, 除非使用集合生成器

{ x for x in range(10)} # Generator sets

set([1, 2, 3]) == {1, 2, 3} set((i*2 for i in range(10))) == {i*2 for i in range(10)}

 

比较操作

>>> x = 5
>>> 1 < x < 10
True
>>> 10 < x < 20
False
>>> x < 10 < x*10 < 100
True
>>> 10 > x <= 9
True
>>> 5 == x > 4
True

 

动态创建新类

>>> NewType = type("NewType", (object,), {"x": "hello"})
>>> n = NewType()
>>> n.x'hello'

另一个普通版本

>>> class NewType(object):
>>>     x = "hello"
>>> n = NewType()
>>> n.x"hello"

 

条件赋值

x = 1 if (y == 10) else 2 
x = 3 if (y == 1) else 2 if (y == -1) else 1  

 

变量解包

>>> first,second,*rest = (1,2,3,4,5,6,7,8)
>>> first # The first value1
>>> second # The second value2
>>> rest # All other values
[3, 4, 5, 6, 7, 8]

>>> first,*rest,last = (1,2,3,4,5,6,7,8)
>>> first1>>> rest
[2, 3, 4, 5, 6, 7]
>>> last8
列表元素的序号
>>> l = ["spam", "ham", "eggs"]
>>> list(enumerate(l)) 
>>> [(0, "spam"), (1, "ham"), (2, "eggs")]
>>> list(enumerate(l, 1)) # 指定计数起点
>>> [(1, "spam"), (2, "ham"), (3, "eggs")]

 

异常捕获中使用else

try: 
  function()
except Error:  # If not load the try and declared Error
else:  # If load the try and did not load except
finally:  # Performed anyway

 

列表拷贝

 

错误的做法

>>> x = [1, 2, 3]
>>> y = x
>>> y[2] = 5>>> y
[1, 2, 5]
>>> x
[1, 2, 5]

 

正确的做法

>>> x = [1,2,3]
>>> y = x[:]
>>> y.pop()3>>> y
[1, 2]
>>> x
[1, 2, 3]

 

对于递归列表的做法

import copy
my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]} 
my_copy_dict = copy.deepcopy(my_dict)

 

英文原文: https://www.devbattles.com/en/sand/post-1799-Python_the_things_that_you_might_not_know

译者: 诗书塞外

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics