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

前端 未结 12 2157
遥遥无期
遥遥无期 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.

提交回复
热议问题