Удалить пустые элементы массива python

Удаление пустых элементов из массива/списка в Python

В этом примере внутри all_data_array меня есть два массива:
1. “Пустое”: [[], [], [], [], [], [], [], [], [], []]
2. Заполненный (который очень длинный), [[0, 1, 2, 3], [‘foo’, ‘moo’, ‘bar’, ‘sis’], [’05-03-2014′, ’10-03-2014′, ’14-03-2014′, ’20-03-2014′], [’05-03-2014′, ’10-03-2014′, ’14-03-2014′, ’20-03-2014′], [’12:00′, ’12:03′, ’12:01′, ’12:01′], [’12:05′, ’12:08′, ’12:06′, ’12:06′], [123, 322, 345, 0], [1, 1, 1, 0], [1, 0, 1, 0], [0.1149597018957138, 0.920006513595581, 1.0062587261199951, 1.0062587261199951]]

Как я могу удалить из all_data_array все пустые массивы? Решение для примера – просто all_data_array.pop[0] но я хотел бы иметь общее решение, если это возможно

Я пробовал что-то вроде этого, но он не работает, и я немного потерялся:

for i in all_data_array: for m in xrange(len(all_data_array)): if m == []: print "EMPTY" else: print "WITH CONTENT" 
not_empty_ones = [] for el in all_data_array: if all(el): not_empty_ones.append(el) print not_empty_ones 

Поскольку это список, состоящий из самих списков, вам нужно проверить, все ли элементы внутри пусты или нет. Это может быть достигнуто со всеми встроенными.

all_data_array_no_empty = [x for x in all_data_array if all(x)] 

это сделает это, несмотря на длину пустого массива/списка:

from itertools import chain [array for array in all_data_array if len(list(chain.from_iterable(array))) > 0] 

если ваши списки не пустые, вы получаете разные результаты, если используете all вместо len(list(chain.from_iterable(array))) > 0 :

>>> all_data_array = [[[0], []], [[1, 1, 1]]] >>> [l for l in all_data_array if len(list(chain.from_iterable(l))) > 0] [[[0], []], [[1, 1, 1]]] # >> [el for el in all_data_array if all(el)] [[[1, 1, 1]]] #  

Источник

How to remove none from list python (5 Ways)

remove none from list Python

In this article, we are solving the problem of how to remove none from list python. This type of problem in Python can be solved in many ways, we will be looking in 5 ways to remove none from list in python.

What is none in python?

None is a keyword in Python used to define a null value or no value at all. It is not the same as an empty string or zero, or false value, it is the data type of the class NoneType in Python.

We can declare none variable as –

a = None print("Value of a is", a) print("Type of a is", type(a))

Value of a is None Type of a is

Why should we remove none from list Python?

When analyzing a large set of data, it is likely that we come across with none values or missing values. To make sure data is clean and tidy for data analysis and data representation removing null values from list data in python is important.

Since null values affect the performance and accuracy of machine learning algorithms it is necessary to handle these none values from data sets before applying the machine learning algorithm. Removing such unwanted null values, and corrupting data before processing the algorithm is called data preprocessing.

How to remove none from list Python

The 5 Ways to get rid of none in Python are as follows-

Method 1- Remove none from list using filter() method

The easiest way to remove none from list in Python is by using the list filter() method. The list filter() method takes two parameters as function and iterator. To remove none values from the list we provide none as the function to filter() method and the list which contains none values.

None – To eliminate none values we provide none as the function in the filter method

Iterator – An iterator like list, set, or tuple.

Python Code:

# List with none values sample_list = [1,2, True, None, False, None, 'Python', None] # Using filter() method to filter None values filtered_list = list(filter(None, sample_list)) print("List with None values: ", sample_list) print("List without None values", filtered_list)
List with None values: [1, 2, True, None, False, None, 'Python', None] List without None values [1, 2, True, 'Python']

Method 2- Naive Method

We can also remove none from list in python using a for loop and check whether the values are none if yes ignore it and the rest of the values can be appended to another list.

Python Code:

# List with none values sample_list = [1,2, True, None, False, None, 'Python', None] # initialize filtered list filtered_list = [] # Using for loop for ele in sample_list: if ele != None: filtered_list.append(ele) print("List with None values: ", sample_list) print("List without None values", filtered_list) 
List with None values: [1, 2, True, None, False, None, 'Python', None] List without None values [1, 2, True, 'Python']

Method 3- Using For loop + list remove()

To remove none from list python we will iterate over the list elements and compare each element with none if we find any none element we will remove none element from the list using the python list remove() method.

The list remove() method takes a single lament as an argument and removes that element from the list.

Python Code:

# List with none values sample_list = [1,2, True, None, False, None, 'Python', None] #Printing define list print("List with None values:", sample_list) # Using for loop and remove method for ele in sample_list: if ele == None: sample_list.remove(ele) # print list after removing none print("List without None values:", sample_list) 
List with None values: [1, 2, True, None, False, None, 'Python', None] List without None values [1, 2, True, 'Python']

Method 4- Using List Comprehension

To remove none values from list we also use list comprehension. In Python, list comprehension is a way to create a new list from existing other iterables like lists, sets, and tuples. We can also say that list comprehension is a shorter version of for loop. To know about list comprehension you can visit this.

Python Code:

# List with none values sample_list = [1,2, True, None, False, None, 'Python', None] # Using List comprehension to remove none values filtered_list = [ ele for ele in sample_list if ele is not None ] print("List with None values: ", sample_list) print("List without None values", filtered_list) 
List with None values: [1, 2, True, None, False, None, 'Python', None] List without None values [1, 2, True, 'Python']

Method 5- Using Filter() + lambda function

In python, the lambda function is an anonymous function that is without any name. It takes any number of arguments but can only perform one expression.

As we discuss above filter() method takes a function as input, and since lambda is also one kind of method in python, hence we provide a lambda function and an iterator as input arguments to the filter method.

Example - filter(lambda_function, iterator)

Python code:

# List with none values sample_list = [1,2, True, None, False, None, 'Python', None] # Using filter() method + lambda filtered_list = list(filter(lambda ele:ele is not None, sample_list)) print("List with None values: ", sample_list) print("List without None values", filtered_list)
List with None values: [1, 2, True, None, False, None, 'Python', None] List without None values [1, 2, True, 'Python']

Conclusion

Hence we have seen how to remove none from list python in 5 different ways. We can remove none from list python by using filter(), naive method, for loop + remove(), using list comprehension, and filter() + lambda function.

I am Passionate Computer Engineer. Writing articles about programming problems and concepts allows me to follow my passion for programming and helping others.

Источник

Удалить пустые строки из списка строк в Python

В этом посте мы обсудим, как удалить пустые строки из списка строк в Python.

1. Использование filter() функция

Рекомендуемое решение — использовать встроенную функцию filter(function, iterable) , который строит iterator из элементов iterable для которого указано функция возвращает истину. Если функция None , предполагается тождественная функция, т. е. все элементы iterable, которые являются ложными, удаляются. Вот рабочий пример с использованием фильтров:

Вы также можете пройти len функция для фильтрации пустых строк из списка, как показано ниже:

2. Использование понимания списка

Вы также можете использовать понимание списка для удаления пустых строк из списка строк. Понимание списка состоит из выражения, за которым следует цикл for, за которым следует необязательный цикл for или оператор if, заключенные в квадратные скобки. [] . Обратите внимание, что это решение медленнее, чем подход с фильтром.

3. Использование join() с split() функция

Выражение ' '.join(iterable).split() может использоваться для фильтрации пустых значений из итерации. ' '.join(list) эффективно объединить список строк, разделенных пробелом. затем split() Функция вызывается для результирующей строки, которая возвращает список строк, в которых последовательные пробелы считаются одним разделителем.

4. Использование list.remove() функция

The list.remove("") удаляет только первое вхождение пустой строки из списка. Чтобы удалить все вхождения пустой строки из списка, вы можете воспользоваться тем фактом, что она вызывает ValueError когда он не может найти указанный элемент в списке. Идея состоит в том, чтобы многократно вызывать remove() функционировать до тех пор, пока не возникнет ValueError исключение. Это показано ниже:

Источник

How to Use Python to Remove Zeros from List

To remove zeros from a list using Python, the easiest way is to use list comprehension.

list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0] list_without_zeros = [x for x in list_of_numbers if x != 0] print(list_without_zeros) #Output: [1,4,2,-4,3,-1]

You can also use the Python filter() function.

list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0] list_without_zeros = list(filter(lambda x: x != 0, list_of_numbers)) print(list_without_zeros) #Output: [1,4,2,-4,3,-1]

When working with lists of numbers, it can be valuable to be able to easily filter and remove unwanted values from your list.

One such situation where you may want to remove values from a list is if you have a lot of zeros in your list.

We can easily remove all zeros from a list using Python with list comprehension. List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

Below is the code which will allow you to remove all zeros from a list using list comprehension in Python.

list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0] list_without_zeros = [x for x in list_of_numbers if x != 0] print(list_without_zeros) #Output: [1,4,2,-4,3,-1]

Removing Zeros from List with Python filter() Function

The Python filter() function is a built-in function that allows you to process an iterable and extract items that satisfy a given condition.

We can use the Python filter() function to extract all the items in a list of numbers which do not equal 0 and remove the zeros from a list.

Below is some example code showing you how to remove zeros from a list using the filter() function.

list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0] list_without_zeros = list(filter(lambda x: x != 0, list_of_numbers)) print(list_without_zeros) #Output: [1,4,2,-4,3,-1]

Removing Any Value from List Using Python

In a very similar way, we can remove any value from a list using list comprehension.

For example, if we instead wanted to remove all of the ones from a list, we could do that easily with list comprehension in Python by adjusting the code above.

list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0] list_without_zeros = [x for x in list_of_numbers if x != 1] print(list_without_zeros) #Output: [0,4,2,-4,0,0,3,0,-1,0]

Another example would be if we have a list of strings, and we want to remove the word “whoa”, we can do that with list comprehension in Python.

list_of_strings = ["whoa","there","hey","there","whoa"] filtered_list = [x for x in list_of_strings if x != "whoa"] print(filtered_list) #Output: ["there","hey","there"]

Hopefully this article has been useful for you to learn how to remove zeros from a list in Python.

  • 1. pi in Python – Using Math Module and Leibniz Formula to Get Value of pi
  • 2. Python Even or Odd – Check if Number is Even or Odd Using % Operator
  • 3. How to Shutdown Computer with Python
  • 4. How to Add Commas to Numbers in Python
  • 5. Check if Set Contains Element in Python
  • 6. Using Python to Print Degree Symbol
  • 7. Python Indicator Function – Apply Indicator Function to List of Numbers
  • 8. nunique pandas – Get Number of Unique Values in DataFrame
  • 9. How to Check if String Contains Lowercase Letters in Python
  • 10. Find Quotient and Remainder After Division in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

Читайте также:  Page Title
Оцените статью