如何提高程序效率?现在,它充满了if语句。
import copy
def hexadecimal(a):
z = a.replace('0b','')
y = z.rjust(8,'0')
list1 = list(y)
newlist = []
for i in range(1,5):
nig = list1.pop(0)
newlist.append(nig)
if newlist == ['0','0','0','0']:
valuenew = ''
if newlist == ['0','0','0','1']:
valuenew = '1'
if newlist == ['0','0','1','0']:
valuenew = '2'
if newlist == ['0','1','0','0']:
valuenew = '4'
if newlist == ['1','0','0','0']:
valuenew = '8'
if newlist == ['0','0','1','1']:
valuenew = '3'
if newlist == ['0','1','1','1']:
valuenew = '7'
if newlist == ['0','1','0','1']:
valuenew = '5'
if newlist == ['0','1','1','0']:
valuenew = '6'
if newlist == ['1','0','0','1']:
valuenew = '9'
if newlist == ['1','0','1','0']:
valuenew = 'A'
if newlist == ['1','0','1','1']:
valuenew = 'B'
if newlist == ['1','1','0','0']:
valuenew = 'C'
if newlist == ['1','1','0','1']:
valuenew = 'D'
if newlist == ['1','1','1','0']:
valuenew = 'E'
if newlist == ['1','1','1','1']:
valuenew = 'F'
if list1 == ['0','0','0','0']:
valuenew1 = ''
if list1 == ['0','0','0','1']:
valuenew1 = '1'
if list1 == ['0','0','1','0']:
valuenew1 = '2'
if list1 == ['0','1','0','0']:
valuenew1 = '4'
if list1 == ['1','0','0','0']:
valuenew1 = '8'
if list1 == ['0','0','1','1']:
valuenew1 = '3'
if list1 == ['0','1','1','1']:
valuenew1 = '7'
if list1 == ['0','1','0','1']:
valuenew1 = '5'
if list1 == ['0','1','1','0']:
valuenew1 = '6'
if list1 == ['1','0','0','1']:
valuenew1 = '9'
if list1 == ['1','0','1','0']:
valuenew1 = 'A'
if list1 == ['1','0','1','1']:
valuenew1 = 'B'
if list1 == ['1','1','0','0']:
valuenew1 = 'C'
if list1 == ['1','1','0','1']:
valuenew1 = 'D'
if list1 == ['1','1','1','0']:
valuenew1 = 'E'
if list1 == ['1','1','1','1']:
valuenew1 = 'F'
print(valuenew + valuenew1)
a = str(bin(int(input('enter a number'))))
hexadecimal(a)
该程序仅用于转换最多8位的二进制文件
答案 0 :(得分:2)
答案 1 :(得分:0)
Python已经内置了一些您想要的hex()
。但是,如果您不愿自己编写代码,那么我会对您的代码进行一些调整:
(1)由于python没有switch语句,因此您最好的办法是尝试使用dict
代替;我还介绍了一个hex_digit
函数,该函数基本上只是从HEX_DIGIT
引用您需要的值(您并不是真的需要它,但是如果将来需要替换它,它将抽象该部分)
(2)为填充添加了一些逻辑,因此它不仅适用于 8位长度的数字
HEX_DIGITS = {
'0000': '',
'0001': '1',
'0010': '2',
'0011': '3',
'0100': '4',
'0101': '5',
'0110': '6',
'0111': '7',
'1000': '8',
'1001': '9',
'1010': 'A',
'1011': 'B',
'1100': 'C',
'1101': 'D',
'1110': 'E',
'1111': 'F',
}
def hex_digit(val):
print('Converting: ' , val)
return HEX_DIGITS.get(val, '')
def hexadecimal(a):
z = a.replace('0b','')
len_z = len(z)
# Add padding if len not a factor of 4
if len_z % 4 != 0:
full_length = len_z + (4 - (len_z % 4))
z = z.rjust(full_length, '0')
split_vals = [
hex_digit(z[idx:idx+4])
for idx in range(0,len(z),4)
]
print("Hex value: {}".format("".join(split_vals)))
a = str(bin(int(input('Enter a number: '))))
hexadecimal(a)
答案 2 :(得分:0)
您可以将代表数字的任意字符串文字转换为具有给定基数的整数,然后将该整数转换为字符串。
>> b = '0b01001'
>> format(int(b, 2), 'X')
'9'
>> b = '1001'
>> format(int(b, 2), 'X')
'9'
代码
def hexadecimal(a):
return format(bin(a, 2), 'X') # You could also print it