Skip to content

Instantly share code, notes, and snippets.

@chairco
Last active November 21, 2023 13:21
Show Gist options
  • Save chairco/6bfb4ee42701c3f141665f5b03ea09cd to your computer and use it in GitHub Desktop.
Save chairco/6bfb4ee42701c3f141665f5b03ea09cd to your computer and use it in GitHub Desktop.
Python 其淫技巧大整理

二進位的轉換 str->bin, bin->str

參考: https://www.quora.com/How-do-I-convert-integers-to-binary-in-Python-3

int('0011',2) # 將 0011 轉換成 3

A = [[0,0,1,1], [0,0,0,1]]
return sum(int(''.join(map(str,a)),2) for a in A) #加總這兩個值

十進位轉二進位

"{0:b}".format(10) = 1010
`bin(6)[2:] = 110
`bin(10)[2:].zfill(4) = 1010

二進制轉十進制

int('10100111110',2)

str 轉二進位

As a more pythonic way you can first convert your string to byte array then use bin function within  map :

>>> st = "hello world"
>>> map(bin,bytearray(st))
['0b1101000', '0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111', '0b1101111', '0b1110010', '0b1101100', '0b1100100']
Or you can join it:

>>> ' '.join(map(bin,bytearray(st)))
'0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'
Note that in python3 you need to specify an encoding for bytearray function :

>>> ' '.join(map(bin,bytearray(st,'utf8')))
'0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'
You can also use binascii module in python 2:

>>> import binascii
>>> bin(int(binascii.hexlify(st),16))
'0b110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'
hexlify return the hexadecimal representation of the binary data then you can convert to int by specifying 16 as its base then convert it to binary with bin.

or

 >>> st = "hello world"
>>> ' '.join(format(ord(x), 'b') for x in st)
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

#using `bytearray`
>>> ' '.join(format(x, 'b') for x in bytearray(st))
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

collections

defaultdict

某天在 Python Taiwan 看到有人問個問題是這樣,資料結構如下:

countries = {
    'AAA': {'Tw': ['ssd'], 'Cn': ['ccn']},
    'BBB': {'Tw': ['tte'], 'Cn': ['ggc']}
}

希望變成這樣:

 {'Tw': ['ssd','tte'],'Cn': ['ccn','ggc']}

大概想法就是最外層的 key 應該是無用,只要去 parser 裡頭那層,然後把相同的放在一起。

做法一:

c = list(countries.values())
print(c)
out = {key:value+c[i+1][key] for i in range(len(c)-1) for key, value in c[i].items()}
print(out)

就是把第一層剝掉,然後透過表達式去建新的資料結構,但注意事表達式在 Python 3.x for 迴圈是後到前

做法二:

c = list(countries.values())
print(c)
d = [{key: ','.join(value)} for i in range(len(c)) for key, value in c[i].items()]
print(d) # [{'Tw': 'ssd'}, {'Cn': 'ccn'}, {'Tw': 'tte'}, {'Cn': 'ggc'}]

datas = defaultdict(list)
for data in d:
    for k, v in data.items():
        datas[k].append(v)

print(dict(datas))

# or

d = [(key, ','.join(value)) for i in range(len(c)) for key, value in c[i].items()]
print(d) # [('Tw', 'ssd'), ('Cn', 'ccn'), ('Tw', 'tte'), ('Cn', 'ggc')]

datas = defaultdict(list)
for k, v in d:
    datas[k].append(v)
    
print(dict(datas))

就是本標題,和第一個不一樣在於他透過 defaultdict 去幫你檢查 key,大概就4這樣,要更精簡嗎?

d = [(k, ','.join(v)) for idx, value in enumerate(c) for k, v in value.items()]
print(d) # [('Tw', 'ssd'), ('Cn', 'ccn'), ('Tw', 'tte'), ('Cn', 'ggc')]

datas = defaultdict(list)
for k, v in d:
    datas[k].append(v)
print(dict(datas))

itertools

groupby

把兩層的 list 重新 row, colum 配成一對

>>> array= [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
>>> list(zip(*array))
>>> [(3, 2, 9, 0), (0, 4, 2, 3), (8, 5, 6, 1), (4, 7, 3, 0)]

build-in function

我很喜歡 zip function,

a= [[1,2], 
    [3,4], 
    [5,6]] 

如果要 row, col 互換變成 ([1,3,5], [2,4,6]) 可以這樣 list(zip(*a)) 也引發我的好奇心,到底怎麼做的?

來看一下:

def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)

原來使用了一個 iter 的概念,因為 iter 讀出後就沒有值,所以有點像是用 iter 讀組內 n 個值,然後回傳。美妙

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment