我必须做一些将十六进制转换为二进制,并将它们与一些列表进行比较并显示结果。
转换的部分我已经做了,但比较的部分我正在努力。
bitmap = input("inform your bitmap: ")
h_size = len(bitmap)*4
bitmap = (bin(int(bitmap,16))[2:]).zfill(h_size)
str_bitmap = str(bitmap)
for a,b in enumerate(str_bitmap):
print(a,b)
输出:
inform your bitmap: 7a
0 0
1 1
2 1
3 1
4 1
5 0
6 1
7 0
所以我想得到,当为1时,枚举并与另一个列表进行比较,就像在这种情况下:
1,2,3,4,6 (the 0,5,7 don't go because is 0)
并将从列表中检查并带来如下结果:
1 = bakery
2 = banana
3 = car
4 = house
5 = keyboard
6 = mouse
,最终结果将是:
bakery, banana, car, house, mouse
这样做的方法是什么?
答案 0 :(得分:0)
你可以在字典中输入字符串,然后使用列表理解来选择它们b == '1'
:
>>> str_bitmap = '01111010'
>>> names = {1:'bakery', 2:'banana', 3:'car', 4:'house', 5:'keyboard', 6:'mouse'}
>>> [names[a] for a, b in enumerate(str_bitmap) if b == '1']
['bakery', 'banana', 'car', 'house', 'mouse']
答案 1 :(得分:0)
您可以根据当前枚举的二进制数字打印相应的列表项:
bitmap = input("inform your bitmap: ")
h_size = len(bitmap)*4
bitmap = (bin(int(bitmap, 16))[2:]).zfill(h_size)
str_bitmap = str(bitmap)
items = [
"",
"bakery", #1
"banana", #2
"car", #3
"house", #4
"keyboard", #5
"mouse" #6
]
for i,b in enumerate(str_bitmap):
if b == "1":
print(" {} = {}".format(i, items[i]))
给定"7a"
输出作为输入:
1 = bakery
2 = banana
3 = car
4 = house
6 = mouse