1. 程式人生 > >Python的24個小技巧

Python的24個小技巧

python中相對不常見卻很實用的小竅門

空談不如來碼程式碼吧:


交換變數值

"""pythonic way of value swapping"""
a, b = 5, 10
print(a, b)
a, b = b, a
print(a, b)

給列表元素建立新的分隔符

a = ["Python", "is", "awesome"]
print(" ".join(a))

找列表中出現次數最多的元素

""" most frequent element in a list """
a = [1, 2, 3, 1, 2, 3, 2, 2, 4, 5, 1]
print(max(set(a), key=a.count))

""" using Counter from collections """
from collections import Counter
cnt = Counter(a)
print(cnt.most_common(3))

核對兩個字元是否為迴文

from collections import Counter
str1 = "123456"
str2 = "654321"
if Counter(str1) == Counter(str2):
    print("迴文")

反向輸出字串

""" 方法一 """
a = "abcdefghijkmnopqrstuvwxyz"
print(a[::-1])

""" 方法二 """
for char in reversed(a):
    print(char)

""" 方法三 """
num = 123456789
print(int(str(num)[::-1]))

反向輸出列表

""" 方法一 """
a = [5, 4, 3, 2, 1]
print(a[::-1])

""" 方法二 """
for i in reversed(a):
    print(i)

轉置2維陣列

original = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*original)
print(list(transposed))
# [('a', 'c', 'e'), ('b', 'd', 'f')]

鏈式比較

s = 6
print(3 < s < 8)
print(2 == s < 10)
# True
# False

函式的鏈式寫法

def product(a, b):
    return a * b


def add(a, b):
    return a + b


b = True
print((product if b else add)(5, 7))
# 35

複製列表

a = [1, 2, 3, 4, 5]
b = a
b[0] = 10
print(b)
# [10, 2, 3, 4, 5]

b = a[:]
b[0] = 10
print(b)
# [10, 2, 3, 4, 5]

a = [1, 2, 3, 4, 5]
print(list(a))
# [1, 2, 3, 4, 5]

print(a.copy())
# [1, 2, 3, 4, 5]

from copy import deepcopy
l = [[1, 2], [3, 4]]
l2 = deepcopy(l)
print(l2)
# [[1, 2], [3, 4]]

字典的新增

dicts = {'a': 1, 'b': 2}
print(dicts.get('c', 3))
# 3

對字典的值排序

d = {'a': 10, 'b': 20, 'c': 5, 'd': 1}
print(sorted(d.items(), key=lambda x: x[1]))
# [('d', 1), ('c', 5), ('a', 10), ('b', 20)]

from operator import itemgetter
print(sorted(d.items(), key=itemgetter(1)))
# [('d', 1), ('c', 5), ('a', 10), ('b', 20)]

for else結構

a = [1, 2, 3, 4, 5]
for i in a:
    if i == 0:
        break
else:
    print("did not break out of for loop")

將列表轉換為逗號分隔

l = ['foo', 'bar', 'xyz']
print(','.join(l))
# foo,bar,xyz

num = [2, 3, 4, 5, 10]
print(','.join(map(str, num)))
# 2,3,4,5,10

data = [2, 'hello', 3, 3.4]
print(','.join(map(str, data)))
# 2,hello,3,3.4

字典的合併

d1 = {'a': 1}
d2 = {'b': 2}
# pyhton 3.5
print({**d1, **d2})
# {'a': 1, 'b': 2}

print(dict(d1.items() | d2.items()))
# {'b': 2, 'a': 1}

d1.update(d2)
print(d1)
# {'a': 1, 'b': 2}

找列表中最大、最小值下標

li = [20, 50, 80, 10, 55]


def minIndex(li):
    return min(range(len(li)), key=li.__getitem__)


def maxIndex(li):
    return max(range(len(li)), key=li.__getitem__)


print(minIndex(li))
# 3
print(maxIndex(li))
# 2

從列表中刪除重複項

li = [2, 2, 3, 1, 3, 5, 6, 1]

newli = list(set(li))
print(newli)
# [1, 2, 3, 5, 6]

from collections import OrderedDict
li = ["foo", "bar", "bar", "foo"]
print(list(OrderedDict.fromkeys(li).keys()))
# ['foo', 'bar']

all or any

x = [True, True, False]
if any(x):
    print("至少有一個是True!")

if all(x):
    print("沒有一個是False!")

if any(x) and not all(x):
    print("至少一個True和一個False!")

# 至少有一個是True!
# 至少一個True和一個False!

emoji

from emoji import emojize
print(emojize(":thumbs_up"))

**kwargs

dic = {'a': 1, 'b': 2}


def someFunction(a, b):
    print(a + b)
    return


someFunction(**dic)
someFunction(a=1, b=2)

三元運算

a = 1
b = 5

if (a > b):
    print(a)
else:
    print(b)


print(a) if a > b else print(b)

階乘

i = 1
p = 1
n = input("輸入:")
while i <= int(n):
    p = p * i
    i += 1
print("結果:" + str(p))

set(集合)資料結構

# set(集合)是一個非常有用的資料結構。它與列表(list)的行為類似,區別在於set不能包含重複的值。
# 這在很多情況下非常有用。例如你可能想檢查列表中是否包含重複的元素,
# 你有兩個選擇,第一個需要使用for迴圈,就像這樣:
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']

duplicates = []
for value in some_list:
    if some_list.count(value) > 1:
        if value not in duplicates:
            duplicates.append(value)

print(duplicates)
# 輸出: ['b', 'n']


# 但還有一種更簡單更優雅的解決方案,那就是使用集合(sets),你直接這樣做:
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = set([x for x in some_list if some_list.count(x) > 1])
print(duplicates)
# 輸出: set(['b', 'n'])


# 集合還有一些其它方法,下面我們介紹其中一部分。

# =========交集=========
# 你可以對比兩個集合的交集(兩個集合中都有的資料),如下:
valid = set(['yellow', 'red', 'blue', 'green', 'black'])
input_set = set(['red', 'brown'])
print(input_set.intersection(valid))
# 輸出: set(['red'])


# =========差集===========
# 你可以用差集(difference)找出無效的資料,相當於用一個集合減去另一個集合的資料,例如:
valid = set(['yellow', 'red', 'blue', 'green', 'black'])
input_set = set(['red', 'brown'])
print(input_set.difference(valid))
# 輸出: set(['brown'])


# 你也可以用符號來建立集合,如:
a_set = {'red', 'blue', 'green'}
print(type(a_set))
# 輸出: <type 'set'>

ZIP

keys = ['a', 'b', 'c']
valus = [1, 2, 3]
zippend = dict(zip(keys, valus))
print(zippend)
# {'a': 1, 'b': 2, 'c': 3}

 

如果你覺得我有需改進的地方或者有其他建議請評論,我會繼續更新這個部落格的。