binary_list = [['0', '0', '1', '0', '1'], ['1', '0', '1', '0', '1'], ['0', '0', '0', '0', '0'], ['0', '1', '0', '0', '1'], ['1', '1', '0', '0', '0'], ['0', '0', '1', '0', '1'], ['0', '0', '0', '1', '0'], ['0', '0', '1', '0', '0']]
cipher_value = []
cipher_num = 0
for list in binary_list:
for num in range(len(list)):
if num == 0 and list[num] == 1:
cipher_num = 16
elif num == 0 and list[num] == 0:
continue
if num == 1 and list[num] == 1:
cipher_num = 8
elif num == 1 and list[num] == 0:
continue
if num == 2 and list[num] == 1:
cipher_num = 4
elif num == 2 and list[num] == 0:
continue
if num == 3 and list[num] == 1:
cipher_num = 2
elif num == 3 and list[num] == 0:
continue
if num == 4 and list[num] == 1:
cipher_num = 1
elif num == 4 and list[num] == 0:
continue
cipher_value.append(cipher_num)
cipher_num = 0
break
uj5u.com熱心網友回復:
您可以使用int(..., 2)將數字的二進制表示(字串型別)轉換為整數。因此,在join串列理解的幫助下:
cipher_value = [int(''.join(sublist), 2) for sublist in binary_list]
print(cipher_value) # [5, 21, 0, 9, 24, 5, 2, 4]
uj5u.com熱心網友回復:
對于串列中的每個元素,您可以使用位移將二進制表示形式轉換為十進制整數。這具有能夠處理可變數量的二進制數以及可變長度的二進制數的優點:
binary_list = [['0', '0', '1', '0', '1'], ['1', '0', '1', '0', '1'], ['0', '0', '0', '0', '0'], ['0', '1', '0', '0', '1'], ['1', '1', '0', '0', '0'], ['0', '0', '1', '0', '1'], ['0', '0', '0', '1', '0'], ['0', '0', '1', '0', '0']]
cipher_values = []
for binary_repr in binary_list:
cipher_num = 0
for bit in binary_repr:
cipher_num <<= 1
cipher_num = int(bit)
cipher_values.append(cipher_num)
print(cipher_values)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/411463.html
標籤:
上一篇:為什么回圈將NA值添加到資料幀?
