【问题标题】:Remove none values in this list using python [duplicate]使用python删除此列表中的无值[重复]
【发布时间】:2019-08-03 16:07:15
【问题描述】:

我想删除此列表中的 None 值

input= [(None, 'Ibrahimpatnam', 9440627084, None, 'Under Investigation'),
        (None, 'Ibrahimpatnam', 9440627084, None, 'Under Investigation')]

并得到类似的输出

['Ibrahimpatnam', 9440627084, 'Under Investigation', 'Ibrahimpatnam', 9440627084, 'Under Investigation']

【问题讨论】:

    标签: python


    【解决方案1】:

    您需要遍历列表(其中包含元组),然后遍历每个元组。检查每个元组的每个元素是否为None

    a = [
        (None, "Ibrahimpatnam", 9_440_627_084, None, "Under Investigation"),
        (None, "Ibrahimpatnam", 9_440_627_084, None, "Under Investigation"),
    ]
    b = [element for sub_tuple in a for element in sub_tuple if element is not None]
    print(b)
    

    你得到

    ['Ibrahimpatnam', 9440627084, '正在调查中', 'Ibrahimpatnam', 9440627084, '正在调查中']

    【讨论】:

    • @Hayat 这就是 OP 要求的,不是吗?
    • 是的..当然没看到。
    【解决方案2】:

    试试这个:

    input_= [(None, 'Ibrahimpatnam', 9440627084, None, 'Under Investigation'),
            (None, 'Ibrahimpatnam', 9440627084, None, 'Under Investigation')]
    output = []
    for each in input_:
        newList = list(filter(None,each))
        output = output+newList
    print(output)
    

    注意:不要使用input作为变量,它是python中的保留关键字。如果您刚刚在这篇文章中使用它,那也没关系。

    【讨论】:

      【解决方案3】:

      如果你想剥离,那么连接——列表理解在这里工作得非常干净而不会失去可读性:

      import itertools
      stripped_lists = [ [x for x in sublist if x] for sublist in input_ ]
      
      print(list(itertools.chain.from_iterable(stripped_lists )))
      

      输出:

      ['Ibrahimpatnam', 9440627084, 'Under Investigation', 'Ibrahimpatnam', 9440627084, 'Under Investigation']
      

      或者,如果你连接然后剥离,这很好而且很短:

      print(list(x for x in itertools.chain.from_iterable(aa) if x))
      

      【讨论】:

        【解决方案4】:

        首先,使用列表推导展平数据,然后使用filter() 方法过滤掉 None 值。 filter() 方法将返回一个过滤器对象。所以我们必须使用list() 方法将其转换回列表:

        flat_input = [item for sublist in input for item in sublist]
        output = list(filter(None, flat_input))
        

        这是我能想到的最短的解决方案。希望对您有所帮助!

        【讨论】:

          【解决方案5】:

          如果子列表项不是无则迭代列表然后子列表添加到新列表b

          a = [
              (None, "Ibrahimpatnam", 9_440_627_084, None, "Under Investigation"),
              (None, "Ibrahimpatnam", 9_440_627_084, None, "Under Investigation"),
          ]
          b=[]
          for i in a:
              for j in i:
                  if j:
                      b.append(j)
          
          
          print (b)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-04-04
            • 1970-01-01
            • 1970-01-01
            • 2014-07-14
            • 1970-01-01
            • 1970-01-01
            • 2012-03-20
            • 2011-10-04
            相关资源
            最近更新 更多