Home > Net >  convert a list of strings of ints to list of tuples
convert a list of strings of ints to list of tuples

Time:05-11

If I have a list that looks like this below of strings that are int values:

['10 90', '10 -90', '100 45', '20 180']

How would I convert it to a list of tuples? Like this:

[(10,90), (10,-90), (100,45), (20,180)]

This code below doesn't change the original list as I think lists in Python are mutable where I can change the values directly versus creating a new list of correct values. What's best approach?

newlines = []
for string in lines:
    newlines.append(tuple(string))

prints:

[('1', '0', ' ', '9', '0'), ('1', '0', ' ', '-', '9', '0'), ('1', '0', '0', ' ', '4', '5'), ('2', '0', ' ', '1', '8', '0')]

CodePudding user response:

You have to split each string first. Then convert each split item to an integer; finally convert the pair to a tuple:

out = [tuple(map(int, item.split())) for item in lst]

Output:

[(10, 90), (10, -90), (100, 45), (20, 180)]

CodePudding user response:

You could probably do it with map and list comprehension, but for clarity's sake let's use simple loop:

values=['10 90', '10 -90', '100 45', '20 180']
result=[]
for x in values:
    pair=x.split()
    pair=tuple(map(int, pair))
    result.append(pair)
print(result)

CodePudding user response:

You can try this, should give you the same outcome, the old_lst is the list you want transformed. You should also get a similar result with item.partition(' ') but you would have to incorporate extra steps to pop out the space in the returned data.

old_lst = ['10 90', '10 -90', '100 45', '20 180']
new_lst = []

for item in old_lst:
    pair=item.split(' ')
    new_lst.append(tuple(pair))

Outcome:

[('10', '90'), ('10', '-90'), ('100', '45'), ('20', '180')]
  • Related