可能會(huì)用的pyhton小知識(shí)點(diǎn)

交換值

>>> 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]

擴(kuò)展列表

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

列表負(fù)數(shù)索引

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

列表切片

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[3:6] # 第3個(gè)到第6個(gè)之間的元素
[3, 4, 5]
>>> a[:5] # 前5個(gè)元素
[0, 1, 2, 3, 4]
>>> a[5:] # 后5個(gè)元素
[5, 6, 7, 8, 9]
>>> a[::] # 所有元素(拷貝列表)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::2] # 偶數(shù)項(xiàng)
[0, 2, 4, 6, 8]
>>> a[1::2] # 奇數(shù)項(xiàng)
[1, 3, 5, 7, 9]
>>> a[::-1] # 反轉(zhuǎn)列表
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

二維數(shù)組變一維數(shù)組

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

列表推導(dǎo)式

>>> le = [x * 2 for x in range(10)]
>>> le # 每個(gè)數(shù)取2倍
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

>>> le = [x for x in range(10) if x % 2 == 0]
>>> le # 獲取偶數(shù)項(xiàng)
[0, 2, 4, 6, 8]

生成器表達(dá)式

>>> 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

集合推導(dǎo)式

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

字典推導(dǎo)式

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

合并兩個(gè)字典

>>> 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")
>>>

三元運(yùn)算

>>> 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'}

兩個(gè)列表轉(zhuǎn)換字典

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

反轉(zhuǎn)字典

>>> 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

默認(rèn)字典

>>> 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]

設(shè)置字典的默認(rèn)值

>>> 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]}

頻數(shù)統(tǒng)計(jì)

>>> 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 無(wú)序
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個(gè)數(shù)

>>> 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")

打開(kāi)文件

>>> with open('foo.txt', 'w') as f:
...     f.write("hello")
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容