[英]How to convert string to this type of list in Python
我正在使用一个库,它返回一个 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(" ")
两者都是列表...但是当我稍后在代码中运行此 function 时,出现错误:
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
....do something
使用列表理解和 map 的元素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]
Output:
[(92, 254, 228, 118), (148, 661, 262, 547)]
beer44 有一个很好的答案,只是为了展示 map 节省了多少工作:
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]
Output:
[(92, 254, 228, 118), (148, 661, 262, 547)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.