简体   繁体   中英

Convert string to int in a list by removing floating (Python)

I have a list like this:

List= [("Mike,"Admin","26,872"),
       ("John,"Admin","32,872"),
       ("Mark,"Admin","26,232")...]

what I want to achieve is the following:

List= [("Mike,"Admin", 26872),
       ("John,"Admin", 32872),
       ("Mark,"Admin", 26232)...]

so for the every third element I want to remove comma and convert it to int. I tried for example to do replace but the list doesn't support replace method.

Just a test:

    accounts = sorted(List, key=lambda account: account[2], reverse=True)
    for i,j,k in accounts:
         k.replace(",", "")
         int k

Any ideas?

One way would be:

[(a, b, c.replace(",", "")) for a, b, c in List]

This will create a new list having the first two values unchanged, and the third with the comma being removed.

If you want to have the third value as an int , you can simply.. cast it.

Note that you can iterate on the list in a different way,

[(w[0], w[1], w[2]) for w in List]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM