Editing strings in a list of lists

后端 未结 5 702
一向
一向 2021-01-23 08:50

I\'ve made a list of lists from a text block where each list contains all the words in a line as a separate element, like this:

listoflists = [[\'Lorem\', \'ipsu         


        
相关标签:
5条回答
  • 2021-01-23 08:57

    Why don't you just do return n.strip('\n')? You can get rid of the if/else

    0 讨论(0)
  • 2021-01-23 09:01
    listoflists = [['Lorem', 'ipsum', 'dolor', 'sit', 'amet\n'],['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis\n']]
    for l in listoflists:
        l[-1] = l[-1].replace('\n','')
    print listoflists
    

    """ Output:

    [['Lorem', 'ipsum', 'dolor', 'sit', 'amet'], ['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis']]

    """

    0 讨论(0)
  • 2021-01-23 09:03

    Also, the reason your original code does not work is b/c n.strip('\n') does not change the value of n. It returns a new string. If you did something like n=n.strip('\n'); return n, that would work.

    0 讨论(0)
  • 2021-01-23 09:12

    Just iterate over each list and replace the last element with the last element with the '\n' stripped.

    >>> listoflists = [['Lorem', 'ipsum', 'dolor', 'sit', 'amet\n'],
                   ['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis\n']]
    >>> for elem in listoflists:
            elem[-1] = elem[-1].strip('\n')
    
    
    >>> listoflists
    [['Lorem', 'ipsum', 'dolor', 'sit', 'amet'], ['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis']]
    

    EDIT - Since in the code, you seem to be stripping \n from each element you could do

    >>> [[elem.strip('\n') for elem in lst] for lst in listoflists]
    [['Lorem', 'ipsum', 'dolor', 'sit', 'amet'], ['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis']]
    
    0 讨论(0)
  • 2021-01-23 09:16

    You could use a list comprehension

    listoflists = [['Lorem', 'ipsum', 'dolor', 'sit', 'amet\n'],
                   ['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis\n']]
    
    [[j.replace("\n","") for j in i] for i in listoflists]
    

    Output

    [['Lorem', 'ipsum', 'dolor', 'sit', 'amet'],
     ['consectetur', 'adipiscing', 'elit', 'donec', 'iaculis']]
    
    0 讨论(0)
提交回复
热议问题