简体   繁体   English

如何在 Python 中将字符串转换为此类列表

[英]How to convert string to this type of list in Python

I am using a library, that is returning a Python list.我正在使用一个库,它返回一个 Python 列表。

When I print that list it looks like this:当我打印该列表时,它看起来像这样:

print(face_locations)
[(92, 254, 228, 118), (148, 661, 262, 547)]
print(type(face_locations))
<class 'list'>

I have a string with values: "92 254 228 118;148 661 262 547" .我有一个带有值的字符串: "92 254 228 118;148 661 262 547"

I want to convert this string to the same datatype.我想将此字符串转换为相同的数据类型。

What I did so far:到目前为止我做了什么:

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(" ")

Both are lists...But When I run this function later in my code, I get an error:两者都是列表...但是当我稍后在代码中运行此 function 时,出现错误:

for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings): 
    ....do something

Use list comprehension and map the elements of str to int .使用列表理解和 map 的元素strint

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: Output:

[(92, 254, 228, 118), (148, 661, 262, 547)]

beer44 has a great answer and just to show how much work map saves: 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: Output:

[(92, 254, 228, 118), (148, 661, 262, 547)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM