【问题标题】:Pick up names and find an 'n' inside the list and create a new list [duplicate]拿起名字并在列表中找到一个'n'并创建一个新列表[重复]
【发布时间】:2019-06-06 03:38:35
【问题描述】:

我正在尝试从随机名称列表中创建一个新列表。我想挑选这些随机名称并创建一个名称中包含字母“n”的新列表。

有什么想法吗?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    试试这个:

    rand_names = [ 'john', 'shawn', 'steve' ]
    names = [ name for name in rand_names  if 'n' in name]
    print(names)
    

    【讨论】:

      【解决方案2】:

      使用过滤列表理解。

      names = ['john', 'shawn', 'steve']
      names_with_n = [name for name in names if 'n' in name]
      

      输出:

      >>> names_with_n
      ['john', 'shawn']
      >>> 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-16
        • 1970-01-01
        • 2020-09-07
        • 1970-01-01
        • 2022-11-22
        相关资源
        最近更新 更多