Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

python - Create a new list from a list when a certain condition is met

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...