2016-06-13 175 views
-1

我必須做一些將十六進制轉換爲二進制,並將它們與某個列表進行比較並顯示結果。將一個列表與另一個列表進行比較並顯示結果

轉換的部分我已經做了,但是我正在努力進行比較的部分。

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

你可以在一個字典中的字符串,然後使用列表理解來接他們,如果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'] 
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 
相關問題