2

I have a tuple a = (('1414', 'A'), ('1416', 'B')) and I need to obtain the result as result = ((1414, 'A'), (1416, 'B')).

I tried tuple([map(int, x[0]) for x in a]) based on How to convert strings into integers in Python? and I get the result as ([1414], [1416]). How would I maintain the result as a tuple with the changed value instead of making it as a list?

4 Answers4

4

Using a generator expression:

a = (('1414', 'A'), ('1416', 'B'))

result = tuple((int(x[0]), x[1]) for x in a)
user94559
  • 57,357
  • 6
  • 98
  • 99
2

Using map:

azip = list(zip(*a))
out = list(zip(map(int, azip[0]), azip[1]))
Gerges
  • 5,869
  • 2
  • 20
  • 37
0

You can use a lambda in map() which converts the first element in the tuple to an int.

a = (('1414', 'A'), ('1416', 'B'))
result = tuple(map(lambda x: (int(x[0]), x[1]), a))
bgfvdu3w
  • 1,163
  • 9
  • 16
0

You can do :

print(tuple([(int(i[0]),i[1]) for i in a]))

for detailed solution :

a = (('1414', 'A'), ('1416', 'B'))

new_list=[]

for i in a:
    new_list.append((int(i[0]),i[1]))

print(tuple(new_list))
Aaditya Ura
  • 10,695
  • 7
  • 44
  • 70