当满足特定条件时,从列表创建新列表

2024-10-01 22:28:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从另一个单词列表中创建一个新列表;当单词的某个条件满足时。在本例中,我想将所有长度为9的单词添加到一个新列表中

我使用了:

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

删除长度小于4的所有条目。但是,我现在不想删除这些条目。我想用这些单词创建一个新列表,但要将它们保留在旧列表中

也许是这样的:

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

Tags: in列表forlenifnot条目条件
3条回答

试试这个:

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

尝试:

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

抱歉,意识到您想要的是长度9,而不是长度9或更大

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

相关问题 更多 >

    热门问题