How to truncate all strings in a list to a same length, in some pythonic way?

前端 未结 3 1106
别跟我提以往
别跟我提以往 2021-01-11 15:22

Let\'s say we have a list such as:

g = [\"123456789123456789123456\", 
     \"1234567894678945678978998879879898798797\", 
     \"654654656465656565656565565         


        
相关标签:
3条回答
  • 2021-01-11 15:52

    Use a list comprehension:

    [elem[:12] for elem in g]
    
    0 讨论(0)
  • 2021-01-11 15:54

    Another option is to use map(...) :

    b = map(lambda x: x[:9],g)
    
    0 讨论(0)
  • 2021-01-11 16:09

    Use a list comprehension:

    g2 = [elem[:12] for elem in g]
    

    If you prefer to edit g in-place, use the slice assignment syntax with a generator expression:

    g[:] = (elem[:12] for elem in g)
    

    Demo:

    >>> g = ['abc', 'defg', 'lolololol']
    >>> g[:] = (elem[:2] for elem in g)
    >>> g
    ['ab', 'de', 'lo']
    
    0 讨论(0)
提交回复
热议问题