[英]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.