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?

  • What would the code look like to turn `b = ('1414', 'A')` into `1414`? It would just be `int(b[0])`, right? No reason to use `map`? So, what happens if you then try applying *that logic* to the overall tuple of tuples? BTW, the described output does not match; in 2.x it would result in `([1, 4, 1, 4], [1, 4, 1, 6])`, and in 3.x the result is a pair of `map` objects. Considering the 2.x result carefully makes it clear where the fault is. But at any rate, this problem is caused by a typo and/or not reproducible. – Karl Knechtel May 18 '23 at 21:26
  • Alternately: if the goal is to consider a tuple and convert only the values that are convertible *while preserving the other values*, and getting the tuple back - that is a different problem entirely. – Karl Knechtel May 18 '23 at 21:27

4 Answers4

4

Using a generator expression:

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

result = tuple((int(x[0]), x[1]) for x in a)
user94559
  • 59,196
  • 6
  • 103
  • 103
2

Using map:

azip = list(zip(*a))
out = list(zip(map(int, azip[0]), azip[1]))
Gerges
  • 6,269
  • 2
  • 22
  • 44
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,548
  • 1
  • 12
  • 17
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
  • 12,007
  • 7
  • 50
  • 88