PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 19, 2022

[FIXED] How to convert a tuple list string value to integer

 July 19, 2022     integer, list, python-3.x, string, tuples     No comments   

Issue

I have the following list:

l = [('15234', '8604'), ('15238', '8606'), ('15241', '8606'), ('15243', '8607')]

I would like to converted it such that the tuple values are integers and not string. How do I do that?

Desired output:

[(15234, 8604), (15238, 8606), (15241, 8606), (15243, 8607)]

What I tried so far?

l = [('15234', '8604'), ('15238', '8606'), ('15241', '8606'), ('15243', '8607')]
new_list = []
        for i in `l:
            new_list.append((int(i[0]), i[1]))

        print(tuple(new_list))

This only converts the first element i.e. 15234, 15238, 15241, 15243 into int. I would like to convert all the values to int. How do I do that?


Solution

The easiest and most concise way is via a list comprehension:

>>> [tuple(map(int, item)) for item in l]
[(15234, 8604), (15238, 8606), (15241, 8606), (15243, 8607)]

This takes each tuple in l and maps the int function to each member of the tuple, then creates a new tuple out of them, and puts them all in a new list.



Answered By - MattDMo
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing