简体   繁体   中英

How to convert string to this type of list in Python

I am using a library, that is returning a Python list.

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" .

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:

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 .

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

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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