rotalcomo
rotalcomo

Reputation: 81

Convert a list of strings to a list of tuples in python

I have a list of strings in this format:

['5,6,7', '8,9,10']

I would like to convert this into the format:

[(5,6,7), (8,9,10)]

So far I have tried this:

[tuple(i.split(',')) for i in k]

And I obtain:

[('5','6','7'), ('8','9','10')]

I am a bit stuck on how to simply convert the strings into tuples of integers. Thank you

Upvotes: 4

Views: 4707

Answers (4)

Hep Alem
Hep Alem

Reputation: 1

listA = ['21, 3', '13, 4', '15, 7']
# Given list
print("Given list : \n", listA)
# Use split
res = [tuple(map(int, sub.split(', '))) for sub in listA]
# Result
print("List of tuples: \n",res)

source: https://homiedevs.com/example/python-convert-list-of-strings-to-list-of-tuples#64288

Upvotes: 0

Tim Skov Jacobsen
Tim Skov Jacobsen

Reputation: 3852

The following solution is for me the most readable, perhaps it is for others too:

a = ['5,6,7', '8,9,10']          # Original list
b = [eval(elem) for elem in a]   # Desired list

print(b)

Returns:

[(5, 6, 7), (8, 9, 10)]

The key point here being the builtin eval() function, which turns each string into a tuple. Note though, that this only works if the strings contain numbers, but will fail if given letters as input:

eval('dog')

NameError: name 'dog' is not defined

Upvotes: 3

jrd1
jrd1

Reputation: 10716

Your question requires the grouping of elements. Hence, an appropriate solution would be:

l = ['5','6','7', '8','9','10']
[(lambda x: tuple(int(e) for e in x))((i,j,k)) for (i, j, k) in zip(l[0::3], l[1::3], l[2::3])]

This outputs:

[(5, 6, 7), (8, 9, 10)]

As desired.

Upvotes: 1

user3398633
user3398633

Reputation:

If your strings are strings representation of number, then:

[tuple(int(s) for s in i.split(',')) for i in k]

Upvotes: 4

Related Questions