Home > Software design >  CONVERT STRING IN ARRAY
CONVERT STRING IN ARRAY

Time:10-11

I have to convert a string element like this:

["[['plane1.png', '[-1.0, -1.0, 0.9999999999999999, -1.4501078562170397, -3.0908559322343176, 2.7628911124920634]'], ['plane1.png', '[-1.0, -1.0, 0.9999999999999999, -1.4501078562170397, -3.0908559322343176, 2.7628911124920634]'], ['plane1.png', '[-1.0, -1.0, 0.9999999999999999, -1.4501078562170397, -3.0908559322343176, 2.7628911124920634]']]"]

into something like this:

[['plane1.png', '[-1.0, -1.0, 0.9999999999999999, -1.4501078562170397, -3.0908559322343176, 2.7628911124920634]'], ['plane1.png', '[-1.0, -1.0, 0.9999999999999999, -1.4501078562170397, -3.0908559322343176, 2.7628911124920634]'], ['plane1.png', '[-1.0, -1.0, 0.9999999999999999, -1.4501078562170397, -3.0908559322343176, 2.7628911124920634]']]

I tried using this

sequence = np.fromstring(sequence[0: (self.sequence_len - 1)], sep=']],[[')

but it's not working. If any of you have some idea

CodePudding user response:

Try ast.literal_eval:

from ast import literal_eval

lst = [
    "[['plane1.png', '[-1.0, -1.0, 0.9999999999999999, -1.4501078562170397, -3.0908559322343176, 2.7628911124920634]'], ['plane1.png', '[-1.0, -1.0, 0.9999999999999999, -1.4501078562170397, -3.0908559322343176, 2.7628911124920634]'], ['plane1.png', '[-1.0, -1.0, 0.9999999999999999, -1.4501078562170397, -3.0908559322343176, 2.7628911124920634]']]"
]

lst = literal_eval(lst[0])
print(lst)

Prints:

[
    [
        "plane1.png",
        "[-1.0, -1.0, 0.9999999999999999, -1.4501078562170397, -3.0908559322343176, 2.7628911124920634]",
    ],
    [
        "plane1.png",
        "[-1.0, -1.0, 0.9999999999999999, -1.4501078562170397, -3.0908559322343176, 2.7628911124920634]",
    ],
    [
        "plane1.png",
        "[-1.0, -1.0, 0.9999999999999999, -1.4501078562170397, -3.0908559322343176, 2.7628911124920634]",
    ],
]

If you want to further parse the sub-lists:

for l in lst:
    l[1] = literal_eval(l[1])

print(lst)

Prints:

[
    [
        "plane1.png",
        [
            -1.0,
            -1.0,
            0.9999999999999999,
            -1.4501078562170397,
            -3.0908559322343176,
            2.7628911124920634,
        ],
    ],
    [
        "plane1.png",
        [
            -1.0,
            -1.0,
            0.9999999999999999,
            -1.4501078562170397,
            -3.0908559322343176,
            2.7628911124920634,
        ],
    ],
    [
        "plane1.png",
        [
            -1.0,
            -1.0,
            0.9999999999999999,
            -1.4501078562170397,
            -3.0908559322343176,
            2.7628911124920634,
        ],
    ],
]
  • Related