【问题标题】:Remove nested list if nested list contains a number at an index如果嵌套列表在索引处包含数字,则删除嵌套列表
【发布时间】:2020-11-20 12:55:46
【问题描述】:

如果嵌套列表在特定索引处包含特定数字,我想删除该嵌套列表。

列表示例:

permutations_list = [[9, 7, 14, 4, 2, 10], [9, 7, 2, 10, 14, 4], [9, 7, 2, 10, 4, 14], [9, 7, 2, 14, 10, 4], [9, 7, 2, 14, 4, 10], [9, 7, 2, 4, 10, 14], [9, 7, 2, 4, 14, 10], [9, 7, 4, 10, 14, 2], [9, 7, 4, 10, 2, 14], [9, 7, 4, 14, 10, 2], [9, 7, 4, 14, 2, 10], [9, 7, 4, 2, 10, 14], [9, 7, 4, 2, 14, 10]]

我想要检查每个嵌套列表是否在索引 4 处包含数字 14。如果发生这种情况,请删除任何符合这些规范的嵌套列表,从而生成以下列表列表:

permutations_list = [[9, 7, 14, 4, 2, 10], [9, 7, 2, 10, 4, 14], [9, 7, 2, 14, 10, 4], [9, 7, 2, 14, 4, 10], [9, 7, 2, 4, 10, 14], [9, 7, 4, 10, 2, 14], [9, 7, 4, 14, 10, 2], [9, 7, 4, 14, 2, 10], [9, 7, 4, 2, 10, 14]]

这是我尝试过的:

for i in permutations_list:
    for c in i:
        if c =='10' and c[4]:
            permutations_list.remove(i)

所有这些都会导致:

TypeError: 'int' object is not subscriptable

【问题讨论】:

    标签: python-3.x list list-comprehension typeerror nested-lists


    【解决方案1】:

    您可以只循环一次主列表并检查此列表中索引 4 处的元素是否为 14。如果是14,删除它,如果不是,什么也不做。就像我在下面做的那样

    for i in permutations_list :
       if i[4] == 14 :
          permutations_list.remove(i)
    

    【讨论】:

      【解决方案2】:

      使用列表推导

      例如:

      permutations_list = [[9, 7, 14, 4, 2, 10], [9, 7, 2, 10, 14, 4], [9, 7, 2, 10, 4, 14], [9, 7, 2, 14, 10, 4], [9, 7, 2, 14, 4, 10], [9, 7, 2, 4, 10, 14], [9, 7, 2, 4, 14, 10], [9, 7, 4, 10, 14, 2], [9, 7, 4, 10, 2, 14], [9, 7, 4, 14, 10, 2], [9, 7, 4, 14, 2, 10], [9, 7, 4, 2, 10, 14], [9, 7, 4, 2, 14, 10]]
      permutations_list = [i for i in permutations_list if not i[4] == 14]
      print(permutations_list)
      

      或使用filter

      permutations_list = list(filter(lambda x: x[4] != 14, permutations_list))
      

      输出:

      [[9, 7, 14, 4, 2, 10],
       [9, 7, 2, 10, 4, 14],
       [9, 7, 2, 14, 10, 4],
       [9, 7, 2, 14, 4, 10],
       [9, 7, 2, 4, 10, 14],
       [9, 7, 4, 10, 2, 14],
       [9, 7, 4, 14, 10, 2],
       [9, 7, 4, 14, 2, 10],
       [9, 7, 4, 2, 10, 14]]
      

      【讨论】:

      • 两者都能完美运行。虽然,在我的大型数据池中运行时使用filter 似乎稍快一些。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 1970-01-01
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      相关资源
      最近更新 更多