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

前端 未结 12 2150
遥遥无期
遥遥无期 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:27

    using the itertools recipe to flatten a list you could do this:

    from itertools import chain
    
    mylist = ['dog', 'cat', 'mouse_bear', 'lion_tiger_rabbit', 'ant']
    
    new_list = list(chain.from_iterable(item.split('_') for item in mylist))
    print(new_list) 
    # ['dog', 'cat', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']
    

    ...or does the import statement violate your one-liner requirement?

提交回复
热议问题