简体   繁体   中英

How to remove the '' (empty string) in the list of list in python?

I want to remove the empty string ('') in the list of list in python.

My input is

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

My expected output should be like:

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

I am new to python i just to tried this (Note* below tried code is not intended)

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)

Can some one help on me achieve the expected output? in the generic way.

You can use a list comprehension to check if any values exist within the sub list, and a nested comprehension to only retrieve those that have a value

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

You can use a nested list comprehension with any that checks if list contains at least one string not empty:

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

Try the below

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

output

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

Assuming the strings inside the list of list doesn't contain , then

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

But if the strings in the list of list can contain , then

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

You could do the following (Using my module 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)

Use a list comprehension to find all sublists that contain any value. Then use a filter to get all entries in this sublist that contain a value (here checked with bool ).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM