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?

2
  • 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. Commented May 18, 2023 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. Commented May 18, 2023 at 21:27

4 Answers 4

4

Using a generator expression:

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

result = tuple((int(x[0]), x[1]) for x in a)
Sign up to request clarification or add additional context in comments.

Comments

2

Using map:

azip = list(zip(*a))
out = list(zip(map(int, azip[0]), azip[1]))

Comments

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))

Comments

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.