【问题标题】:Create a new list from a list when a certain condition is met满足特定条件时从列表创建新列表
【发布时间】:2011-11-16 09:54:53
【问题描述】:

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

我用过:

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

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

大概是这样的:

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

【问题讨论】:

    标签: python list append conditional-statements


    【解决方案1】:

    抱歉,知道您想要长度为 9,而不是长度为 9 或更大。

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

    【讨论】:

      【解决方案2】:

      试试:

      新列表 = []
      对于 resultVital 中的项目:
          如果 len(item) == 9:
              newlist.append(item)

      【讨论】:

        【解决方案3】:

        试试这个:

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

        【讨论】:

        • 检查编辑页面底部右侧的格式提示。请正确格式化您的代码,使其更易于阅读。
        【解决方案4】:

        试试这个:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-27
          • 2019-08-19
          • 1970-01-01
          • 2020-06-27
          • 2021-06-26
          • 1970-01-01
          • 2022-08-24
          • 2023-01-04
          相关资源
          最近更新 更多