Как обнулить массив в питоне

от admin

Стереть весь массив Python

Я хочу сделать это, чтобы я мог хранить в нем новые значения (новый набор из 100 поплавков) и находить минимум.

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

4 ответы

Обратите внимание, что list и array это разные классы. Ты можешь сделать:

Это фактически изменит ваш существующий список. Ответ Дэвида создает новый список и присваивает его той же переменной. Что вы хотите, зависит от ситуации (например, есть ли у любой другой переменной ссылка на тот же список?).

Печать / PDF a и b каждый раз, чтобы увидеть разницу.

ответ дан 17 авг.

Неужели в Python есть массивы? Я не знал этого. (На самом деле я, наверное, знал, но забыл) В любом случае +1 за расширение различий между нашими ответами. Я просто предположил, что разница не будет иметь значения для ОП. — Дэвид З

понятно. это помогает @david: да, для меня нет большой разницы. но моя новизна уменьшилась 😛 — пжехён

«массивы разные»: не совсем, del работает; посмотри мой ответ — Джон Мачин

@Джон, я не имел в виду del не будет работать, просто списки и массивы разные. — Мэтью Флашен

установит array быть пустым списком. (Кстати, в Python они называются списками, а не массивами)

Если это не работает для вас, отредактируйте свой вопрос, включив в него пример кода, демонстрирующий вашу проблему.

ответ дан 17 авг.

Вот как вы повторно инициализируете массив, если делаете это в цикле. Это в основном правильный ответ на вопрос ОП. — Рене Дюшан

Я предпочитаю этот подход, поскольку он исходит из фона VBA, который мы используем array = («») очень похожи и легко запоминаются! +1 — Дин

Да, массивы существуют, и нет, они ничем не отличаются от списков, когда речь идет о таких вещах, как del и append :

Отличия, которые стоит отметить: вам нужно указать тип при создании массива, и вы экономите память за счет дополнительного времени преобразования между типом C и типом Python, когда вы это делаете. arr[i] = expression or arr.append(expression) lvalue = arr[i]

ответ дан 17 авг.

Слишком мало ответов знают разницу между питоном array тип и список Python. +1 для вас. — Кевин Андерсон

Это тонко, но важно сказать, что если список находится в иерархии объектов, в некоторых случаях мы потеряем его ссылку, если просто сделаем foo = [] , поскольку мы определяем новый список для «foo». По этой причине «вверх» для del foo[:] , потому что в этом случае мы модифицируем исходный список «foo». Спасибо! = Д — Эдуардо Лучио

Теперь, чтобы ответить на вопрос, который, возможно, вы должны были задать, например: «Я где-то получаю 100 чисел с плавающей запятой; нужно ли мне поместить их в массив или список, прежде чем я найду минимум?»

Удалить все элементы из списка Python

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

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

list.clear() — рекомендуемое решение в Python 3 для удаления всех элементов из списка.

2. Использование назначения среза

Вы можете очистить список, заменив все элементы пустым списком.

Но просто делать a = [] не очистит список. Он просто создает новый список и привязывает его к переменной a , но старый список и ссылки на него остаются в памяти. Например,

Вы можете очистить весь список, назначив слайсу пустой список, т.е. a[:] = [] .

3. Использование del утверждение

Вы также можете использовать del оператор для удаления содержимого всего списка. Это показано ниже:

Это все об удалении всех элементов из списка в Python.

Оценить этот пост

Средний рейтинг 4.56 /5. Подсчет голосов: 9

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования ��

4 Ways to Clear a Python List

Python Clear List Cover Image

In this tutorial, you’ll learn four different ways to use Python to clear a list. You’ll learn how to use the clear method, the del statement, the *= operator, and list item re-assignment. Knowing how to clear a list is a task that should seem easy, but is an often elusive skill. After reading this tutorial, you’ll have learned four different ways to clear a Python list in order to start fresh.

The Quick Answer: Use clear

Quick Answer - Python Clear List

Table of Contents

What are Python Lists?

Lists in Python are one of the main data structures that exist in the language. They have some unique attributes, similar to arrays in other languages. They can hold values of different data types, meaning that they’re heterogeneous. They are also ordered, meaning that you can access the items by their index position. Python list indices start at 0 and increment by 1. Python lists can also contain duplicate values.

How does Python List Indexing Work

In the next section, you’ll learn how to clear a Python list with the .clear() method.

Clear a Python List with Clear

One of the easiest ways to clear a Python list is to the use the list.clear() method. The method empties a given list and doesn’t return any items. The method was introduced in Python 3.2, so if you’re using an earlier version, you’ll need to read on to learn how to use the del operator.

Читать:
Как изменить яркость экрана в windows 11

Let’s see how we can empty a list by using the clear method:

Let’s break down what we did above:

  1. We instantiated a list
  2. We then applied the clear method to empty the list
  3. We print the list to ensure that the list is emptied

Now that we know how to use the clear method, we can explore some additional properties about it. The method doesn’t accept any arguments and it modifies a list in place (meaning that we don’t re-assign it to another list).

In the next section, you’ll learn how to empty a Python list with the del keyword.

Want to learn how to pretty print a JSON file using Python? Learn three different methods to accomplish this using this in-depth tutorial here.

Clear a Python List with del

The Python del keyword allows us to delete a particular list item or a range of list items at particular indices. If you want to learn how to use the Python del keyword to delete list items, check out my in-depth tutorial here. Since we can use the Python del keyword to delete items or ranges of items in a list, we can simply delete all items in the list using the : operator.

Let’s see how we can use the del keyword to empty a Python list:

Let’s break down what we did here:

  1. We instantiated a Python list, items
  2. We then used the del keyword to delete items from the first to the last index
  3. We then printed the list to make sure it was empty

Interestingly, the .clear() method works exactly the same as the del [:] keyword, under the hood. It really just represents syntactical sugar in order to make the process a little easier to understand.

In the next section, you’ll learn how to empty a Python list using the *= operator.

Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!

Clear a Python List with the *= Operator

Python allows us to chain operators together. For example, writing a = a + 1 is the same as writing a += 1 . Another way to chain operators is to use the *= , which reassigns the variable multiplied by zero. When we apply this operator a list, we assign the value of 0 to each item, thereby removing the items from the list.

Let’s see how we can use the *= operator to empty a Python list of all of its elements:

In the next section, you’ll learn how to use Python to empty a list using list item re-assignment.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

Clear a Python List with List Item Re-assignment

While it may seem intuitive to empty a list simply by writing some_list = [] . This approach doesn’t actually delete the items from the list, it just removes the reference to the items. If the list has also been assigned to another variable, it’ll be retained in memory.

We can, however, assign the full range of items to be empty items. This will delete all of the items in a list, thereby clearing it.

Let’s see how we can do this with Python:

In the example above, we can see that we re-assigned all of the list items by using the list indexing method. We were able to access all of the items and assign them an empty value.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Conclusion

In this tutorial, you learned four different ways to use Python to clear a list. You learned how to use the .clear() method, the del keyword, the *= operator, and list item re-assignment. Being able to work with lists in different ways is an important skill for a Pythonista of any level.

To learn more about Python lists, check out the official documentation here.

Как обнулить массив в питоне

Return a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those entries not returned by arr[obj].

Parameters arr array_like

obj slice, int or array of ints

Indicate indices of sub-arrays to remove along the specified axis.

Changed in version 1.19.0: Boolean indices are now treated as a mask of elements to remove, rather than being cast to the integers 0 and 1.

The axis along which to delete the subarray defined by obj. If axis is None, obj is applied to the flattened array.

Returns out ndarray

A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place. If axis is None, out is a flattened array.

Похожие статьи