John Bott
John Bott

Reputation: 385

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

Upvotes: 0

Views: 74

Answers (2)

neutrino_logic
neutrino_logic

Reputation: 1299

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

Upvotes: 1

Saleem Ali
Saleem Ali

Reputation: 1383

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

Upvotes: 5

Related Questions