简体   繁体   中英

Python convert hex value from 0x00 to 0x0

I have 2 lists of hex numbers and I need to check whether each item of one list exist in the second list and if so to delete it. The problem is that in the first list the hex numbers are in the format: 0x00 (if they < 0x10) and the second list the hex numbers are in format 0x0. when running the code, it's not delete the item in case in first list = 0x00 and in the second list = 0x0 and I want that in this case, this item will removed

diff = second_hex_list            
for item in first_hex_list:
    if item in second_hex_list:
        diff.remove(item)

Just convert them to int for comparison. You have a second bug where you didn't copy the list before making changes (it should be diff = second_hex_list[:] ). But a list comprehension is a better way to filter this one.

second = set(int(item, 16) for item in second_hex_list)
diff = [item for item in first_hex_list if int(item, 16) not in second]

You could transform the item to match the second list's format before searching:

diff = second_hex_list            
for item in first_hex_list:
    if item.replace("0x0","0x") in second_hex_list:
        diff.remove(item)

This will cover the specific issue you described but may not be appropriate for all cases in actual data (hence the need for you to provide a meaningful example of input and expected output).

Note that, if your lists are very large, you may want to use a set to do the filtering efficiently:

first_hex_set = { item.replace("0x0","0x") for item in first_hex_list }
diff = [item for item in second_hex_list if item not in first_hex_set ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM