可以將sorted與自定義鍵一起使用,例如:lst = [56,209,81,42]
def order_in_reversed_bits_python(lst):
w = len('{:0b}'.format(len(lst)))
return [v for _, v in sorted(enumerate(lst), key=lambda k: '{:0{width}b}'.format(k[0], width=w)[::-1])]
print(order_in_reversed_bits_python(lst))
列印:[56, 81, 209, 42]
計時:import timeit
from random import randint
def order_in_reversed_bits_python(lst):
w = len('{:0b}'.format(len(lst)))
return [v for _, v in sorted(enumerate(lst), key=lambda k: '{:0{width}b}'.format(k[0], width=w)[::-1])]
def order_in_reversed_bits(data):
tobinary = lambda t: np.binary_repr(t, width=len(np.binary_repr(data.shape[0]-1)))[::-1]
func = np.vectorize(tobinary)
a = func(np.arange(0,data.shape[0]))
t = np.zeros(data.shape,dtype='float64')
for i,k in enumerate(a):
t[int(k,2)] = data[i]
return t
# create some large array:
lst = np.array([randint(1, 100) for _ in range(2**16)])
t1 = timeit.timeit(lambda: order_in_reversed_bits_python(lst), number=1)
t2 = timeit.timeit(lambda: order_in_reversed_bits(lst), number=1)
print(t1)
print(t2)
列印:0.10853524302365258
0.22635887702926993