简体   繁体   中英

List of a str-tuple & converting str-tuple to tuple in for loop

How do i take a list of a str tuple like this ['(1, 2, 3)', '(4, 5, 6)'] and I want run it through a for loop and get rid of string around it so first one will be (1, 2, 3) and second will be (4,5, 6).

Essentially, the '(1, 2, 3)' converted to (1, 2, 3) without importing any type of modules.

You can use literal_eval from the ast standard library:

from ast import literal_eval

values = ['(1, 2, 3)', '(4, 5, 6)']
result = [literal_eval(v) for v in values]
print(result)  # [(1, 2, 3), (4, 5, 6)]

A more classic way could be

result = []
for value in values:
    parsed_v = value.strip("()").replace(' ', '').split(",")
    result.append(tuple(int(p) for p in parsed_v))
print(result)  # [(1, 2, 3), (4, 5, 6)]


# expand it
result = []
for value in values:
    parsed_v = value.strip("()").replace(' ', '').split(",")
    tmp = list()
    for p in parsed_v:
        tmp.append(int(p))
    result.append(tuple(tmp))
print(result)  # [(1, 2, 3), (4, 5, 6)]

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