How can I replace a text delimited string list item with multiple list items in a python list?

前端 未结 12 2147
遥遥无期
遥遥无期 2020-12-11 05:17

Given a list:

mylist = [\'dog\', \'cat\', \'mouse_bear\', \'lion_tiger_rabbit\', \'ant\']

I\'d like a one-liner to return a new list:

相关标签:
12条回答
  • 2020-12-11 05:37

    One-liners are over-rated. Here's a solution using a "traditional" for loop.

    mylist = ['dog', 'cat', 'mouse_bear', 'lion_tiger_rabbit', 'ant']
    
    out = []
    for s in mylist:
        if '_' in s:
            out.extend(s.split('_'))
        else:
            out.append(s)
    
    print(out)
    

    output

    ['dog', 'cat', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']
    

    This also works:

    out = []
    for s in mylist:
        out.extend(s.split('_'))
    

    It's shorter, but I think the previous version is clearer.

    0 讨论(0)
  • 2020-12-11 05:37

    You can try this:

    from itertools import chain
    
    mylist = ['dog', 'cat', 'mouse_bear', 'lion_tiger_rabbit', 'ant']
    
    new_list = list(chain(*[[i] if "_" not in i else i.split("_") for i in mylist]))
    

    Output:

    ['dog', 'cat', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']
    
    0 讨论(0)
  • 2020-12-11 05:38
    mylist = ['dog', 'cat', 'mouse_bear', 'lion_tiger_rabbit', 'ant']
    animals = [a for item in mylist for a in item.split('_')]
    print (animals)
    
    0 讨论(0)
  • 2020-12-11 05:40

    This is not a one liner, but is nevertheless a valid option to consider if you want to return a generator:

    def yield_underscore_split(lst):
         for x in lst:
             yield from x.split('_')
    

    >>> list(yield_underscore_split(mylist))
    ['dog', 'cat', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']
    

    Original answer valid only for versions Python 3.3-3.7, kept here for interested readers. Do not use!

    >>> list([(yield from x.split('_')) for x in l]) 
    ['dog', 'cat', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']
    
    0 讨论(0)
  • 2020-12-11 05:43

    Split each item into sublists and flatten them:

    [item for sublist in mylist for item in sublist.split("_")]

    0 讨论(0)
  • 2020-12-11 05:45

    what I would actually do:

    newlist = []
    
    for i in mylist:
        newlist += i.split('_')
    
    0 讨论(0)
提交回复
热议问题