1

I have the code

l = [('1',['3','1','2']),('2',['4','5','2'])]

How do I make it:

l = [(1,[3,1,2]),(2,[4,5,2])]

SwaggyJh
  • 35
  • 4
  • 1
    Does this answer your question? [How to convert elements(string) to integer in tuple in Python](https://stackoverflow.com/questions/34168806/how-to-convert-elementsstring-to-integer-in-tuple-in-python) – Kirill Korolev Nov 16 '19 at 22:32
  • Since tuples are immutable - you should iterate over your collections and recreate it. – sashaaero Nov 16 '19 at 22:33
  • Please update your question with the code you have tried. – quamrana Nov 16 '19 at 22:36

3 Answers3

1

You can use int function while iterating using list comprehension

r = [tuple([int(i),[int(k) for k in j]]) for i,j in l]
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
0

This can be generalised using recursion:

def to_ints(item):
    if isinstance(item, list):
        return [to_ints(e) for e in item]
    elif isinstance(item, tuple):
        return tuple(to_ints(e) for e in item)
    else:
        return int(item)
quamrana
  • 37,849
  • 12
  • 53
  • 71
-1

A simple approach is to remove the quotes and parse it back to a list

 l = eval(str(l).replace("'", ""))
Marsilinou Zaky
  • 1,038
  • 7
  • 17
  • Please do not use `eval` for something like this that can be accomplished easily using built-in features. – Josh Karpel Nov 16 '19 at 23:14
  • Well you might be right that eval not necessarily a best practice, but in this case I can't see a drawback to it. Can you explain your reasoning? – Marsilinou Zaky Nov 17 '19 at 00:30
  • There's some existing discussion [here](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice). – Josh Karpel Nov 17 '19 at 00:35
  • I read that post before posting my answer. None of the disadvantages stated are relevant to the OPs question other than the time difference which is still not a drastic difference. Actually using eval here saves time of looping on the list and it's sublists. – Marsilinou Zaky Nov 17 '19 at 00:46