這是一個使用的解決方案。我在那裏留下了一些調試打印,以顯示它的工作原理。它取任何整數,該整數中的字節數(用於填充目的),以及所需的組大小。請注意,最後一個組可能包含少於group_size數字。
import itertools
# https://docs.python.org/3/library/itertools.html#itertools-recipes
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.zip_longest(fillvalue=fillvalue, *args)
def count_ones(num, total_bits, group_size):
# Turn the original number to a string of ones and zeros
num_bin_str = bin(num)[2:]
# That discards any zeros that are supposed to be on the left
# so pad it with those if necessary
padded_bin_str = '0' * (total_bits - len(num_bin_str)) + num_bin_str
print(padded_bin_str)
for g in grouper(group_size, padded_bin_str, 0):
print(g)
yield sum(map(int, filter(None, g)))
for i in count_ones(0b10011, 8, 2):
print(i)
了許多0b10011
的輸出,是真正爲兩個組大小的8位號碼:
00010011
('0', '0')
0
('0', '1')
1
('0', '0')
0
('1', '1')
2
以下是我認爲這將有一個64位數字的工作要砍下60位和計數1的
# So, starting with a 64 bit integer (I'm just picking one at random here)
# make sure that the number isn't bigger than 64 bits, otherwise I'm not sure if the following trick will work
import random
n = random.randint(0, 2**64 - 1)
# change the first 4 bits to 0 so they don't screw every thing up
# basically I want to generate 64 bits of 1's,
# discard the leftmost 4, and & it with n
# check this- not sure it's 100% correct
n &= ((2**64 - 1) >> 4)
# Now, I should have a large number, but the first ones are 0s
for ones in count_ones(n, 60, 8):
print(ones)
和輸出是:
000000001011001000010110010000101100100001011001000010110010
('0', '0', '0', '0', '0', '0', '0', '0')
0
('1', '0', '1', '1', '0', '0', '1', '0')
4
('0', '0', '0', '1', '0', '1', '1', '0')
3
('0', '1', '0', '0', '0', '0', '1', '0')
2
('1', '1', '0', '0', '1', '0', '0', '0')
3
('0', '1', '0', '1', '1', '0', '0', '1')
4
('0', '0', '0', '0', '1', '0', '1', '1')
3
('0', '0', '1', '0', 0, 0, 0, 0)
1 # Note that we ran out of bits before group size so it's filling it with zeros
謝謝,這將工作。我正在將此函數應用於我從中加載的數據框。將使用此功能。 – ejshin1
很高興幫助!只要一定要測試它!你能接受答案嗎? – Ben
當然,我還有一個問題,但。如果我應用'num = num >> 4',要保留56個叮咬並捨棄4個最左邊的有效位,它會說「TypeError:不支持的操作數類型爲>>:'float'和'int'」 。有沒有其他辦法可以做到這一點? – ejshin1