根据特定条件从列表中创建新列表
我想从一个单词列表中创建一个新列表,条件是单词满足某个特定的要求。在这个例子中,我想把所有长度为9的单词添加到一个新列表中。
我之前用过:
resultReal = [y for y in resultVital if not len(y) < 4]
来删除所有长度小于4的单词。不过现在我不想删除这些单词。我想创建一个新列表来存放这些单词,同时保留旧列表里的单词。
也许可以这样做:
if len(word) == 9:
newlist.append()
4 个回答
2
试试这个:
newlist = [word for word in words if len(word) == 9]
3
试试这个:
newlist = [] for item in resultVital: if len(item) == 9: newlist.append(item)
34
抱歉,我刚才明白你想要的是长度为9,而不是长度大于等于9。
newlist = [word for word in words if len(word) == 9]