[Python] Convert list of strings with "k" suffix for "thousand" to list of numbers

Discussão em 'Python' iniciado por Stack, Março 23, 2025.

  1. Stack

    Stack Membro Participativo

    How to get list that looks like likes to likes_clean?

    likes = ['82.3k', '20k', '18.2k', '17.4k', '14.2k', '13.8k', '13k', '11.4k', '9.2k',
    '8.7k', '8k', '7.1k', '6.8k', '5.7k', '5.2k', '4.9k', '4.8k', '4.6k', '4.6k', '4.6k',
    '4.4k', '4.4k', '4.2k', '4k', '4k', '3.6k', '3.6k', '3.3k', '3.2k', '3k']

    likes_clean = [82300, 20000, 18200, 17400, 14200, 13800, 13000, 11400, 9200,
    8700, 8000, 7100, 6800, 5700, 5200, 4900, 4800, 4600, 4600, 4600,
    4400, 4400, 4200, 4000, 4000, 3600, 3600, 3300, 3200, 3000]


    This is what I tried:

    def likes_count(lks):
    lks = likes
    if lks[-1] == 'k':
    return int(float(lks[:-1]) * 1000)
    return int(lks)


    But I'm getting an error when I try to call the function as likes_count(likes):


    TypeError: int() argument must be a string, a bytes-like object or a real number, not 'list'
    ​

    Continue reading...

Compartilhe esta Página