我正在使用一个库,该库返回一个Python列表。
当我打印该列表时,它看起来像这样:
print(face_locations)
[(92, 254, 228, 118), (148, 661, 262, 547)]
print(type(face_locations))
<class 'list'>
我有一个字符串,其值:"92 254 228 118;148 661 262 547"
。
我想将此字符串转换为相同的数据类型。
我到目前为止所做的:
face_locations= "92 254 228 118;148 661 262 547"
face_locations= face_locations.split(";")
for i in range(len(face_locations)):
face_locations[i] = face_locations[i].split(" ")
两个都是列表...但是当我稍后在代码中运行此函数时,出现错误:
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
....do something
答案 0 :(得分:5)
使用列表推导并将str
的元素映射到int
。
face_locations= "92 254 228 118;148 661 262 547"
face_locations= face_locations.split(";")
[tuple(map(int, elem.split(' '))) for elem in face_locations]
输出:
[(92, 254, 228, 118), (148, 661, 262, 547)]
答案 1 :(得分:1)
beer44有一个很好的答案,只是为了显示节省了多少工作图:
face_locations = "92 254 228 118;148 661 262 547"
face_locations = face_locations.split(";")
face_locations = [face_locations[x].split(' ') for x in range(len(face_locations))]
for sublist in face_locations:
for i in range(len(sublist)):
sublist[i] = int(sublist[i])
face_locations = [tuple(sublist) for sublist in face_locations]
输出:
[(92, 254, 228, 118), (148, 661, 262, 547)]