【问题标题】:How to remove the '' (empty string) in the list of list in python?如何删除python列表列表中的''(空字符串)?
【发布时间】:2022-01-06 08:57:17
【问题描述】:

我想删除python中list列表中的空字符串('')。

我的输入

final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]

我的预期输出应该是这样的:

final_list=[['country'],['India']]

我是 python 新手,我只是想尝试一下(注意* 下面的尝试代码不是有意的)

final=[]
for value in final_list:
   if len(set(value))==1:
      print(set(value))
      if list(set(value))[0]=='':
          continue
       else:
           final.append(value)
    else:
        (final.append(value)
        print(final)

有人可以帮助我实现预期的输出吗?以一般的方式。

【问题讨论】:

    标签: python python-3.x list python-2.7 tuples


    【解决方案1】:

    您可以使用列表推导来检查子列表中是否存在任何值,并使用嵌套推导来仅检索具有值的那些

    [[x for x in sub if x] for sub in final_list if any(sub)]
    

    【讨论】:

      【解决方案2】:

      试试下面的

      final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
      lst = []
      for e in final_list:
        if any(e):
          lst.append([x for x in e if x])
      print(lst)
      

      输出

      [['country'], ['India']]
      

      【讨论】:

        【解决方案3】:

        您可以使用带有any 的嵌套列表推导来检查列表是否包含至少一个不为空的字符串:

        >>> [[j for j in i if j] for i in final_list if any(i)]
        [['country'], ['India']]
        

        【讨论】:

          【解决方案4】:

          假设列表列表中的字符串不包含, 那么

          outlist = [','.join(innerlist).split(',') for innerlist in final_list]
          

          但是如果list列表中的字符串可以包含,那么

          outlist = []
          for inlist in final_list:
            outlist.append(s for s in inlist if s != '')
          

          【讨论】:

            【解决方案5】:

            您可以执行以下操作(使用我的模块 sbNative -> python -m pip install sbNative

            
            from sbNative.runtimetools import safeIter
            
            
            final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
            
            for sub_list in safeIter(final_list):
                while '' in sub_list: ## removing empty strings from the sub list until there are no left
                    sub_list.remove('')
            
                if len(sub_list) == 0: ## checking and removing lists in case they are empty
                    final_list.remove(sub_list)
            
            print(final_list)
            

            【讨论】:

              【解决方案6】:

              使用列表推导查找包含任何值的所有子列表。然后使用过滤器获取此子列表中包含值的所有条目(此处使用bool 检查)。

              final_list = [list(filter(bool, sublist)) for sublist in final_list if any(sublist)]
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2020-11-12
                • 1970-01-01
                • 1970-01-01
                • 2011-04-20
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2021-12-07
                相关资源
                最近更新 更多