更新
我已经根据评论更新了代码:
'该函数的预期目标是让你给它一个整数列表和另一个函数将填充的空列表。'
def convert_to_binary(num_list, func_list):
for i in range(len(num_list)):
# Collects the binary string removing '0b'
binary_string = bin(num_list[i])[2:]
# Break the string into a char array (for loop shorthand)
temp = [char for char in binary_string]
# Add the binary array to func_list
func_list.append(temp)
# Pad with 0's
leading_zeros = 8 - len(temp)
for j in range(leading_zeros):
func_list[i].insert(0,'0')
print(func_list)
if __name__ == '__main__':
num_list = range(0, 10)
func_list = []
convert_to_binary(num_list, func_list)
原创
我不太确定在输入之前 ... 中发生了什么 - 或者在 func_list 的状态下,但是我已经做出了这些假设:
num_list = int 数字列表(例如 1 - 10)
func_list = 二进制字符串列表:其中func_list[i] = bin(num_list[i]) 去掉了字符串前面的 0b。
在上述条件下 - 以下将满足您的要求:
def convert_to_binary(num_list, func_list):
for i in range(len(num_list)):
leading_zeros = 8 - len(func_list[i])
# Build an array of the char's in the func_list index
# can be done in shorthand with temp = [char for char in func_list[i][k]]
temp = []
for k in range(len(func_list[i])):
temp.append(func_list[i][k])
# Replace the binary string with binary char array at func_list index
# e.g. '1' becomes ['1']
func_list[i] = temp
# Add 0's to the front of the char array
for j in range(leading_zeros):
func_list[i].insert(0,'0')
print(func_list)
if __name__ == '__main__':
num_list = range(0, 10)
# Create an array of Binary strings
# (for each value in num_list - removing '0b' from the front)
func_list = [bin(i)[2:]for i in num_list]
convert_to_binary(num_list, func_list)
输出:
[['0', '0', '0', '0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0', '0', '0', '1'], ['0', '0', '0', '0', '0', '0', '1', '0'], ['0', '0', '0', '0', '0', '0', '1', '1'], ['0', '0', '0', '0', '0', '1', '0', '0'], ['0', '0', '0', '0', '0', '1', '0', '1'], ['0', '0', '0', '0', '0', '1', '1', '0'], ['0', '0', '0', '0', '0', '1', '1', '1'], ['0', '0', '0', '0', '1', '0', '0', '0'], ['0', '0', '0', '0', '1', '0', '0', '1']]