Python: Create a new list from a list when a certain condition is met

倖福魔咒の 提交于 2019-12-29 04:44:08

问题


I want to make a new list from another list of words; when a certain condition of the word is met. In this case I want to add all words that have the length of 9 to a new list.

I have used :

resultReal = [y for y in resultVital if not len(y) < 4]

to remove all entries that are under the length of 4. However, I do not want to remove the entries now. I want to create a new list with the words, but keeping them in the old list.

Perhaps something like this:

if len(word) == 9:
     newlist.append()

Thanks.


回答1:


Sorry, realized you wanted length, 9, not length 9 or greater.

newlist = [word for word in words if len(word) == 9]



回答2:


Try:

newlist = []
for item in resultVital:
    if len(item) == 9:
        newlist.append(item)



回答3:


try this:

newlist = [word for word in words if len(word) == 9]



回答4:


Try this:

list= [list_word for list_word in words if len(list_word) == 1]


来源:https://stackoverflow.com/questions/7406448/python-create-a-new-list-from-a-list-when-a-certain-condition-is-met

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!