在python中将列表分成4个相等的部分

Divide the list into 4 equal parts in python

我有如下清单

1
list = [' [00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10]']

我想从列表中去掉"["和"]",然后将列表分为4个元素。即

1
output_list = [0x00000000 , 0x00000000 , 0x00000000 , 0x00000010]

感谢您的帮助。

干杯


试试这个

1
2
3
4
5
6
7
8
9
10
11
12
list = [' [00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10]']

#removing [ and ] and extra spaces
string=list[0]
string=string.replace("[","")
string=string.replace("]","")
string=string.replace("","")


output_list=["0x"+string[i:i+8] for i in range(0,len(string),8)]
print(output_list)
#['0x00000000', '0x00000000', '0x00000000', '0x00000010']

这是一个简单的方法。只需从列表中取出字符串,然后首先移除方括号。然后,只需遍历这个字符串,并在每个部分的开头添加0x

如果输出应该是整数而不是字符串的列表:

1
2
output_list=[int("0x"+string[i:i+8],16) for i in range(0,len(string),8)]
#[0, 0, 0, 16]


步骤1

1
l = mylist[0].strip(' []').split(' ')

输出:

1
['00', '00', '00', '00', '00', '00', '00', '00', '00', '00', '00', '00', '00', '00', '00', '10']

步骤2

1
parts = [l[x:x+4] for x in range(0, len(l), 4)]

输出:

1
2
3
4
[['00', '00', '00', '00'],
 ['00', '00', '00', '00'],
 ['00', '00', '00', '00'],
 ['00', '00', '00', '10']]

步骤3

1
output_list = ['0x%s' % ''.join(p) for p in parts]

输出:

1
['0x00000000', '0x00000000', '0x00000000', '0x00000010']

要获得整数,只需这样做:

1
[int(op, 16) for op in output_list]

输出:

1
[0, 0, 0, 16]