• 两个变量值互换

>>> a=1
>>> b=2
>>> a,b=b,a
>>> a
2
>>> b
1
  • 连续赋值

a = b = c = 50
  • 自动解包

>>> a,b,c = [1,2,3]
>>> a
1
>>> b
2
>>> c
3
>>>
>>>
>>> a, *others = [1,2,3,4]
>>> a
1
>>> others
[2, 3, 4]
>>>
  • 链式比较

a = 15
if (10 < a < 20):
    print("Hi")

等价于

a = 15
if (a>10 and a<20):
    print("Hi")
  • 重复列表

>>> [5,2]*4
[5, 2, 5, 2, 5, 2, 5, 2]
  • 三目运算

age = 30
slogon = "牛逼" if  age == 30 else "niubility"

等价于

if age = 30:
    slogon = "牛逼"
else:
    slogon = "niubility"
  • 字典合并

>>> a= {"a":1}
>>> b= {"b":2}
>>> {**a, **b}
{'a': 1, 'b': 2}
>>>
  • 字符串翻转

>>> s = "i love python"
>>> s[::-1]
'nohtyp evol i'
>>>
  • 列表转字符串

>>> s = ["i", "love", "pyton"]
>>> " ".join(s)
'i love pyton'
>>>
  • for else语句

    检查列表中是否有0,有就提前结束查找,没有的话就算打印未发现
found = False
for i in foo:
    if i == 0:
        found = True
        break
if not found: 
    print("未发现")

如果用for循环配合if,则酱紫

for i in foo:
    if i == 0:
        break
else:
    print("未发现")
  • 字典推导式

>>> m = {x: x**2 for x in range(5)}
>>> m
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>>>
  • 用counter查找列表中出现最多的元素

>>> content = ["a", "b", "c", "a", "d", "c", "a"]
>>> from collections import Counter
>>> c = Counter(content)
>>> c.most_common(1)
[('a', 3)]
>>>
  • 默认值字典

    给字典中的value设置为列表
>>> d = dict()
if 'a' not in d:
    d['a'] = []
d['a'].append(1)

使用defaultdict默认字典构建一个初始值为空列表的字典

from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
  • 赋值表达式

>>> import re
>>> data = "hello123world"
>>> match = re.search("(\d+)", data)  # 3
>>> if match:                         # 4
...     num = match.group(1)
... else:
...     num = None
>>> num
'123
  • http分享文件

    python3

    python3 -m http.server

    python2

    python -m SimpleHTTPServer 8000

  • 查找列表中出现次数最多的数字

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 5]
>>> max(set(test), key=test.count)
4
  • 判断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")
>>>
  • 使用slots解释内存

class MyClass(object):
    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier
        self.set_up()

print(sys.getsizeof(MyClass))


class MyClass(object):
    __slots__ = ['name', 'identifier']
    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier
        self.set_up()

print(sys.getsizeof(MyClass))

In Python 3.5.2
1-> 1016
2-> 888

???这md语法 这就不行了。。不写了。。

版权声明:如无特殊说明,文章均为本站原创,转载请注明出处

本文链接:http://kkxl95.cn/article/1610525084/