How to split strings inside a list by whitespace characters

前端 未结 4 1596
走了就别回头了
走了就别回头了 2020-11-30 11:57

So stdin returns a string of text into a list, and multiple lines of text are all list elements. How do you split them all into single words?

mylist = [\'thi         


        
4条回答
  •  自闭症患者
    2020-11-30 12:41

    Besides the list comprehension answer above that i vouch for, you could also do it in a for loop:

    #Define the newlist as an empty list
    newlist = list()
    #Iterate over mylist items
    for item in mylist:
     #split the element string into a list of words
     itemWords = item.split()
     #extend newlist to include all itemWords
     newlist.extend(itemWords)
    print(newlist)
    

    eventually your newlist will contain all split words that were in all elements in mylist

    But the python list comprehension looks much nicer and you can do awesome things with it. Check here for more:

    https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

提交回复
热议问题