Python replace none in list

Заменить None в словаре Python

У меня есть сложный словарь (со списками, dicts внутри списков и т.д.). Значения для некоторых ключей устанавливаются как Нет Есть ли способ заменить этот None на какое-то значение по умолчанию моего собственного, независимо от сложной структуры словаря?

Да, но, насколько я знаю, быстрого подхода нет, вы должны пересечь dict и любые значения в нем, которые являются контейнерами, заменяя None на ходу. Это звучит как хорошая работа для рекурсии.

@MariusSiuram, да, мой дикт похож на тот, который ты выложил. Разница в том, что у меня не будет None внутри списка. Ничто не будет значением внутри вложенного слова, и я намерен заменить их все

6 ответов

Вы можете сделать это, используя модуль object_pairs_hook из json :

def dict_clean(items): result = <> for key, value in items: if value is None: value = 'default' resultPython replace none in list = value return result dict_str = json.dumps(my_dict) my_dict = json.loads(dict_str, object_pairs_hook=dict_clean) 

Не уверен, что оптимально, но определенно довольно элегантно. Однако, это может потерпеть неудачу, если дикт содержит какой-либо несериализуемый объект.

Рекурсивный из решения Лутца:

def replace(any_dict) for k, v in any_dict.items(): if v is None: any_dict[k] = "my default value" elif type(v) == type(any_dict): replace(v) replace(my_dict) 

Здесь рекурсивное решение, которое также заменяет None внутри списков.

Сначала мы определяем простой класс Null для замены None .

class Null(object): def __repr__(self): return 'Null' NULL = Null() def replace_none(data): for k, v in data.items() if isinstance(data, dict) else enumerate(data): if v is None: data[k] = NULL elif isinstance(v, (dict, list)): replace_none(v) # Test data = < 1: 'one', 2: ['two', 2, None], 3: None, 4: , 5: < 5: [55, 56, None], 6: , 8: [88, , 100] > > print(data) replace_none(data) print(data) 
, 5: , 100], 5: [55, 56, None], 6: >> , 5: , 100], 5: [55, 56, Null], 6: >> 
for k, v in my_dict.items(): if v is None: my_dict[k] = "my default value" 

Вопрос о явном None кажется довольно явным, поэтому я должен сообщить, что v is None а not v , так как этот последний параметр будет изменять пустые строки, ложные значения, число 0 .

@LutzHorn Это решение будет работать, если значение находится на первом уровне. В моем случае значение глубоко внутри dict (внутри dict в списке внутри dict), и решение терпит неудачу

Читайте также:  Не открывается html документ

Вы можете сделать это с помощью рекурсивной функции, которая выполняет итерацию по всем dicts и спискам:

def convert(obj): if type(obj) == list: for x in obj: convert(x) elif type(obj) == dict: for k, v in obj.iteritems(): if v is None: obj[k] = 'DEFAULT' else: convert(v) data = ]> convert(data) print data # -> ]> 

Источник

Python replace none in list

Last updated: Feb 3, 2023
Reading time · 6 min

banner

# Table of Contents

# Remove None values from a list in Python

Use a list comprehension to remove the None values from a list in Python.

The new list will contain all values from the original list, except for the None values.

Copied!
my_list = [1, None, 3, None, 8, None] new_list = [i for i in my_list if i is not None] print(new_list) # 👉️ [1, 3, 8]

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

This solution doesn’t mutate the original list, it returns a new list that doesn’t contain any None values.

Alternatively, you can use the filter function.

# Remove None values from a list using filter()

This is a three-step process:

  1. Use the filter() function to filter out the None values.
  2. Use the list() class to convert the filter object to a list.
  3. The new list won’t contain any None values.
Copied!
my_list = [1, None, 3, None, 8, None] new_list = list(filter(lambda x: x is not None, my_list)) print(new_list) # 👉️ [1, 3, 8]

The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

The lambda function gets called with each item from the list, checks if the value is not None and returns the result.

The last step is to use the list() class to convert the filter object to a list.

Alternatively, you can use a simple for loop.

# Remove None values from a list using a for loop

This is a four-step process:

  1. Declare a new variable that stores an empty list.
  2. Iterate over the original list.
  3. Check if each item is not None .
  4. Use the list.append() method to append items that meet the condition to the new list.
Copied!
my_list = [1, None, 3, None, 8, None] new_list = [] for item in my_list: if item is not None: new_list.append(item) print(new_list) # 👉️ [1, 3, 8]

We used a for loop to iterate over the list.

On each iteration, we check if the current item is not None and if the condition is met, we append the item to the new list.

Читайте также:  Вывод текущего месяца php

The new list won’t contain any None values.

Alternatively, you can mutate the original list.

# Remove None values from the original list using a while loop

You can also use a while loop to remove the None values from a list.

Copied!
my_list = [1, None, 3, None, 8, None, None, None, None] while None in my_list: my_list.remove(None) print(my_list) # 👉️ [1, 3, 8]

The condition of the while loop iterates for as long as there are None values in the list.

On each iteration, we use the list.remove() method to remove a None value from the list.

Once the condition is no longer met and the list doesn’t contain any None values, the while loop exits.

# Remove None values from the original list, in place

This is a three-step process:

  1. Use a for loop to iterate over a copy of the list.
  2. Check if each value is None .
  3. Use the list.remove() method to remove the None values from the list.
Copied!
my_list = [1, None, 3, None, 8, None, None, None] for item in my_list.copy(): if item is None: my_list.remove(item) print(my_list) # 👉️ [1, 3, 8]

This example removes the None values from the original list.

We used the list.copy() method to get a copy of the list.

The list.copy method returns a shallow copy of the object on which the method was called.

However, we can iterate over a copy of the list and remove elements from the original list.

Copied!
my_list = [1, None, 3, None, 8, None, None, None] for item in my_list.copy(): if item is None: my_list.remove(item) print(my_list) # 👉️ [1, 3, 8]

On each iteration, we check if the current item is None and if the condition is met, we use the list.remove() method to remove it.

The list.remove() method removes the first item from the list whose value is equal to the passed in argument.

The remove() method mutates the original list and returns None.

The most important thing to note when removing items from a list while iterating is to use the list.copy() method to iterate over a copy of the list.

If you try to remove elements from the original list while iterating over it, you might run into difficult to locate bugs.

# Remove None values from the original list using filterfalse()

You can also use the filterfalse class from the itertools module to remove the None values from a list.

Copied!
from itertools import filterfalse my_list = [1, None, 3, None, 8, None, None] def null_check(value): return value is None my_list[:] = filterfalse(null_check, my_list) print(my_list) # 👉️ [1, 3, 8]

Make sure to import the filterfalse class from the itertools module as shown in the code sample.

Читайте также:  Php curl response error

The filterfalse method takes a predicate and an iterable and calls the function with each item in the iterable.

The method returns a list containing the items for which the function returned false .

In the example, the method returns a list containing the items that are not None .

# Replace None values in a List in Python

You can use a list comprehension if you need to replace the None values in a list.

Copied!
my_list = ['a', None, 'b', None, 'c', None, None] # 👇️ replace None values in a list with empty string new_list_1 = ['' if i is None else i for i in my_list] print(new_list_1) # 👉️ ['a', '', 'b', '', 'c', '', ''] # 👇️ replace None values in a list with 0 new_list_1 = [0 if i is None else i for i in my_list] print(new_list_1) # 👉️ ['a', 0, 'b', 0, 'c', 0, 0]

The first example replaces None values in a list with an empty string and the second replaces None with 0 .

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

We basically iterate over the list and return an empty string if the item of the current iteration is None , otherwise we return the item as is.

You can use this approach to replace None values with any other value.

# Replace None values in a List using a for loop

Alternatively, you can use a for loop to replace None values in a list.

Copied!
my_list = ['a', None, 'b', None, 'c', None, None] for index, item in enumerate(my_list): if item is None: my_list[index] = '' # 👈️ replaces None with empty string print(my_list) # 👉️ ['a', '', 'b', '', 'c', '', '']

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index, and the second is the item.

Copied!
my_list = ['apple', 'banana', 'melon'] for index, item in enumerate(my_list): print(index, item) # 👉️ 0 apple, 1 banana, 2 melon

On each iteration, we check if the item is None , and if it is, we update the list item at the specific index.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью