本文是我編程時(shí)遇到的一些Python小技巧,總結(jié)出來,不定期更新~
- 二進(jìn)制中的1或0數(shù)量
# bin(n)的結(jié)果是以'0b'開頭的字符串
bin(n).count('1') #1的數(shù)量
bin(n).count('0')-1 #0的數(shù)量
- 字母轉(zhuǎn)數(shù)字
ord('a') #97
- 使用位運(yùn)算字母大小寫轉(zhuǎn)換
def change(a):
a = ord(a) ^ ord(' ')
return chr(a)
# a='f', change(a)='F'
# a='F', change(a)='f'
- 判斷一個(gè)數(shù)的二進(jìn)制是否為1、0交替
# 一個(gè)數(shù)如果是1、0交替,那么它與自身右移一位后異或后并加一
# 結(jié)果應(yīng)該只有一位1,其他位都是0
def check_10switch(n):
tmp = (n ^ (n >>1)) + 1
return bin(tmp).count('1')
- 不使用+-實(shí)現(xiàn)兩個(gè)整數(shù)之和
def getSum(a, b):
while b:
c = a&b
a ^= b
b = c<<1
return a
- collections.Counter().elements
先看看官方解釋:
elements() is one of the functions of Counter class, when invoked on the Counter object will return an itertool of all the known elements in the Counter object.
elements()函數(shù)是Counter下邊的方法,被調(diào)用后會(huì)返回一個(gè)迭代器,迭代器里是一個(gè)Counter對(duì)象的全部元素。
看代碼更好理解:
from collections import Counter
a_o = [1,1,1,2,2]
a = Counter(a_o)
print(a) #Counter({1: 3, 2: 2})
print(a.elements()) #<itertools.chain object at 0x101016588>
print(list(a.elements())) #[1,1,1,2,2]
print(list(a.elements()) == a_o) #True