我有以下字符串:s = "0015CB,0,0,01,006D,0016CF1,4,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,00F4E7D,1,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,0008184,8,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,00FA704,9,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,0014EC8,2,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,00FAEEA,9,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,00FADE9,5,000D,01,0202,01,0E09,01,02,00,006D,0000,0,0,01,006D,00FA5A5,3,000D"Selcuk 好心地協(xié)助在每次迭代時將其拆分,000D因此提取的第一個值是0016CF1,4現(xiàn)在我需要幫助將這個值的第一部分從十六進制轉換為十進制,并將逗號后面的數(shù)字保留原樣。所以它會是93425,4或93425 4到目前為止我有以下內容并且它有效,但不是很優(yōu)雅,請一些人幫助提高效率/清潔度。謝謝。my_list = [e[-9:] for e in s.split(",000D")]print(my_list)# Output = ['0016CF1,4', '00F4E7D,1', '0008184,8', '00FA704,9', '0014EC8,2', '00FAEEA,9', '00FADE9,5', '00FA5A5,3', '']# for testing print the first value from the list [0]# output = 0016CF1,4print(my_list[0])# save my_list in a string called list and remove the comma and check digit# output = 0016CF1list=str(my_list)result = [e[-7:] for e in list.split(",")]print(result[0])# convert the first value from HEX to DEC# output= 93425res1 = int(result[0],16)print(res1)# get the checkdigit for the first value in the listcheckdigit = [f[-1:] for f in s.split(",000D")]print(checkdigit[0])# output = 4# join res1 and checkdigitprint(res1,checkdigit[0])# output = 93425 4理想情況下,我希望在循環(huán)中使用上面的內容,以便原始列表中的所有值都像示例中的第一個值一樣進行轉換。謝謝
1 回答

夢里花落0921
TA貢獻1772條經(jīng)驗 獲得超6個贊
這是一個非常緊湊的解決方案:
my_list = ['0016CF1,4', '00F4E7D,1', '0008184,8', '00FA704,9',
'0014EC8,2', '00FAEEA,9', '00FADE9,5', '00FA5A5,3']
result = [f'{int(x[:-2], 16)} {x[-1]}' for x in my_list]
以下是最終內容result:
['93425 4', '1003133 1', '33156 8', '1025796 9',
'85704 2', '1027818 9', '1027561 5', '1025445 3']
添加回答
舉報
0/150
提交
取消