Почему sort выдает none в python
Перейти к содержимому

Почему sort выдает none в python

  • автор:

Почему «return list.sort ()» возвращает None, а не список?

Я смог проверить, что findUniqueWords приводит к сортировке list . Однако это не return list , почему?

7 ответов

list.sort сортирует список на месте, т.е. он не возвращает новый список. Просто напишите

sort не возвращает отсортированный список; скорее, он сортирует список на месте.

Здесь — это письмо от Guido van Rossum в python dev listifyig, почему он предпочитает не возвращать self для операций, которые влияют на объект и не возвращать новый.

Это происходит из стиля кодирования (популярного на разных языках, я верьте, особенно Lisp упивается в нем), где ряд побочных эффектов на одном объекте можно связать цепочку следующим образом:

который будет таким же, как

Я считаю, что цепочка создает угрозу читаемости; это требует, чтобы читатель должен быть хорошо знаком с каждым из методов. вторая форма дает понять, что каждое из этих вызовов действует на одно и то же объект, и поэтому даже если вы не знаете класс и его методы очень хорошо, вы можете понять, что второй и третий вызов применяются к x (и что все вызовы сделаны для их побочных эффектов), а не что-то еще.

Я хочу зарезервировать цепочку для операций, возвращающих новые значения, как операции строковой обработки:

Обычно Python возвращает None из функций и методов, которые мутируют данные, такие как list.sort , list.append и random.shuffle , при том, что он намекает на то, что он мутировал.

Если вы хотите выполнить итерацию и вернуть новый, отсортированный список своих элементов, используйте встроенную функцию sorted .

Python имеет два вида сортировки: метод сортировки (или «функция-член» ) и функцию сортировки. Метод sort работает над содержимым объекта с именем — считайте его как действие, которое объект берет для переупорядочения. Функция сортировки — это операция над данными, представленными объектом, и возвращает новый объект с тем же содержимым в отсортированном порядке.

Учитывая список целых чисел с именем l , сам список будет переупорядочен, если мы назовем l.sort() :

Этот метод не имеет возвращаемого значения. Но что, если мы попытаемся присвоить результат l.sort() ?

r теперь фактически ничего не значит. Это одна из тех странных, несколько досадных деталей, которые программист, вероятно, забудет после периода отсутствия на Python (вот почему я пишу это, поэтому я не забываю снова).

Функция sorted() , с другой стороны, ничего не сделает с содержимым l , но вернет новый отсортированный список с тем же содержимым, что и l :

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

Чтобы понять, почему он не возвращает список:

sort() не возвращает никакого значения.

Метод sort() просто сортирует элементы данного списка в определенном порядке — по возрастанию или по убыванию, не возвращая никакого значения.

Таким образом, проблема заключается в answer = newList.sort() где нет ответа.

вместо этого вы можете просто return newList.sort()

Синтаксис метода sort():

В качестве альтернативы вы также можете использовать встроенную функцию Python sorted() для той же цели.

Примечание. Простейшей разницей между sort() и sorted() является: sort() не возвращает никакого значения, а sorted() возвращает итерируемый список.

Why does '.sort()' cause the list to be 'None' in Python? [duplicate]

I am attempting to sort a Python list of int s and then use the .pop() function to return the highest one. I have tried a writing the method in different ways:

I have also tried

In both cases .sort() causes the list to be None (which has no .pop() function and returns an error). When I remove the .sort() it works fine but does not return the largest int since the list is not sorted.

8 Answers 8

Simply remove the assignment from

The sort method works in-place (it modifies the existing list), so it returns None . When you assign its result to the name of the list, you’re assigning None . So no assignment is necessary.

But in any case, what you’re trying to accomplish can easily (and more efficiently) be written as a one-liner:

max operates in linear time, O(n), while sorting is O(nlogn). You also don’t need nested list comprehensions, a single generator expression will do.

wjandrea's user avatar

It is a convention in Python that methods that mutate sequences return None .

Python’s Design and History FAQ gives the reasoning behind this design decision (with respect to lists):

Why doesn’t list.sort( ) return the sorted list?

In situations where performance matters, making a copy of the list just to sort it would be wasteful. Therefore, list.sort() sorts the list in place. In order to remind you of that fact, it does not return the sorted list. This way, you won’t be fooled into accidentally overwriting a list when you need a sorted copy but also need to keep the unsorted version around.

In Python 2.4 a new built-in function – sorted() – has been added. This function creates a new list from a provided iterable, sorts it and returns it.

Steven Rumbalski's user avatar

.sort() returns None and sorts the list in place.

This has already been correctly answered: list.sort() returns None . The reason why is «Command-Query Separation»:

Python returns None because every function must return something, and the convention is that a function that doesn’t produce any useful value should return None .

I have never before seen your convention of putting a comment after the line it references, but starting the comment with a carat to point at the line. Please put comments before the lines they reference.

While you can use the .pop() method, you can also just index the list. The last value in the list can always be indexed with -1 , because in Python negative indices «wrap around» and index backward from the end.

But we can simplify even further. The only reason you are sorting the list is so you can find its max value. There is a built-in function in Python for this: max()

Using list.sort() requires building a whole list. You will then pull one value from the list and discard it. max() will consume an iterator without needing to allocate a potentially-large amount of memory to store the list.

Also, in Python, the community prefers the use of a coding standard called PEP 8. In PEP 8, you should use lower-case for function names, and an underscore to separate words, rather than CamelCase.

With the above comments in mind, here is my rewrite of your function:

Inside the call to max() we have a «generator expression» that computes a length for each value in the list paths . max() will pull values out of this, keeping the biggest, until all values are exhausted.

But now it’s clear that we don’t even really need the paths list. Here’s the final version:

I actually think the version with the explicit paths variable is a bit more readable, but this isn’t horrible, and if there might be a large number of paths, you might notice a performance improvement due to not building and destroying the paths list.

Why does '.sort()' cause the list to be 'None' in Python?

Why does ‘.sort()’ cause the list to be ‘None’ in Python?

I am attempting to sort a Python list of int s and then use the .pop() function to return the highest one. I have tried a writing the method in different ways:

I have also tried

In both cases .sort() causes the list to be None (which has no .pop() function and returns an error). When I remove the .sort() it works fine but does not return the largest int since the list is not sorted.

Solution – 1

.sort() returns None and sorts the list in place.

Solution – 2

In Python sort() is an inplace operation. So result.sort() returns None , but changes result to be sorted. So to avoid your issue, don’t overwrite result when you call sort() .

Solution – 3

Simply remove the assignment from

The sort method works in-place (it modifies the existing list), so it returns None . When you assign its result to the name of the list, you’re assigning None . So no assignment is necessary.

But in any case, what you’re trying to accomplish can easily (and more efficiently) be written as a one-liner:

max operates in linear time, O(n), while sorting is O(nlogn). You also don’t need nested list comprehensions, a single generator expression will do.

Solution – 4

list.sort() does not return a list – it destructively modifies the list you are sorting:

That said, max finds the largest element in a list, and will be more efficient than your method.

Solution – 5

Is there any reason not to use the sorted function? sort() is only defined on lists, but sorted() works with any iterable, and functions the way you are expecting. See this article for sorting details.

Also, because internally it uses timsort, it is very efficient if you need to sort on key 1, then sort on key 2.

Solution – 6

It is a convention in Python that methods that mutate sequences return None .

Python’s Design and History FAQ gives the reasoning behind this design decision (with respect to lists):

Why doesn’t list.sort( ) return the sorted list?

In situations where performance matters, making a copy of the list
just to sort it would be wasteful. Therefore, list.sort() sorts the
list in place. In order to remind you of that fact, it does not return
the sorted list. This way, you won’t be fooled into accidentally
overwriting a list when you need a sorted copy but also need to keep
the unsorted version around.

In Python 2.4 a new built-in function – sorted() – has been added.
This function creates a new list from a provided iterable, sorts it
and returns it.

Solution – 7

You don’t need a custom function for what you want to achieve, you first need to understand the methods you are using!

sort() ing a list in python does it in place, that is, the return from sort() is None . The list itself is modified, a new list is not returned.

As you can see, when you try to assign the sort() , you no longer have the list type.

Solution – 8

This has already been correctly answered: list.sort() returns None . The reason why is “Command-Query Separation”:

Python returns None because every function must return something, and the convention is that a function that doesn’t produce any useful value should return None .

I have never before seen your convention of putting a comment after the line it references, but starting the comment with a carat to point at the line. Please put comments before the lines they reference.

While you can use the .pop() method, you can also just index the list. The last value in the list can always be indexed with -1 , because in Python negative indices “wrap around” and index backward from the end.

But we can simplify even further. The only reason you are sorting the list is so you can find its max value. There is a built-in function in Python for this: max()

Using list.sort() requires building a whole list. You will then pull one value from the list and discard it. max() will consume an iterator without needing to allocate a potentially-large amount of memory to store the list.

Also, in Python, the community prefers the use of a coding standard called PEP 8. In PEP 8, you should use lower-case for function names, and an underscore to separate words, rather than CamelCase.

With the above comments in mind, here is my rewrite of your function:

Inside the call to max() we have a “generator expression” that computes a length for each value in the list paths . max() will pull values out of this, keeping the biggest, until all values are exhausted.

But now it’s clear that we don’t even really need the paths list. Here’s the final version:

I actually think the version with the explicit paths variable is a bit more readable, but this isn’t horrible, and if there might be a large number of paths, you might notice a performance improvement due to not building and destroying the paths list.

Почему «.sort ()» приводит к тому, что в Python список «Нет»?

Я пытаюсь отсортировать список Python из int и затем использовать функцию .pop() , чтобы вернуть самый высокий. Я пытался написать метод по-разному:

Я тоже пробовал

В обоих случаях .sort() приводит к тому, что список становится None (который не имеет функции .pop() и возвращает ошибку). Когда я удаляю .sort() , он работает нормально, но не возвращает наибольшее int , поскольку список не отсортирован.

8 ответов

Просто удалите назначение из

Метод sort работает на месте (он изменяет существующий список), поэтому присваивание не требуется и возвращает None . Когда вы присваиваете его результат названию списка, вы назначаете None .

Это может легко (и более эффективно) быть написано как одна строка:

max работает за линейное время O (n), а сортировка — O (nlogn). Вы также не нуждаетесь во вложенных списках, подойдет одно выражение генератора.

list.sort() не возвращает список — он деструктивно изменяет список, который вы сортируете:

Тем не менее, max находит самый большой элемент в списке и будет более эффективным, чем ваш метод.

На этот вопрос уже был дан правильный ответ: list.sort() возвращает None . Причина, по которой «Разделение команд и запросов»:

Python возвращает None , потому что каждая функция должна что-то возвращать, и соглашение состоит в том, что функция, которая не выдает никакого полезного значения, должна возвращать None .

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

Хотя вы можете использовать метод .pop() , вы также можете просто проиндексировать список. Последнее значение в списке всегда можно проиндексировать с помощью -1 , потому что в Python отрицательные индексы «оборачиваются» и индексируются в обратном направлении с конца.

Но мы можем упростить еще дальше. Единственная причина, по которой вы сортируете список, заключается в том, что вы можете найти его максимальное значение. Для этого в Python есть встроенная функция: max()

Использование list.sort() требует построения целого списка. Затем вы извлечете одно значение из списка и откажетесь от него. max() будет использовать итератор без необходимости выделять потенциально большой объем памяти для хранения списка.

Кроме того, в Python сообщество предпочитает использовать стандарт кодирования под названием PEP 8. В PEP 8 вы должны использовать строчные буквы для имен функций и подчеркивание для разделения слов, а не CamelCase.

Имея в виду вышеупомянутые комментарии, вот мое переписывание вашей функции:

Внутри вызова max() у нас есть «выражение генератора», которое вычисляет длину для каждого значения в списке paths . max() будет извлекать значения из этого, сохраняя самые большие, пока все значения не будут исчерпаны.

Но теперь ясно, что нам даже не нужен список paths . Вот финальная версия:

Я на самом деле думаю, что версия с явной переменной paths немного более читабельна, но это не так уж и плохо, и если может быть большое количество путей, вы можете заметить улучшение производительности из-за того, что не собираете и не разрушаете paths список.

Есть ли какая-либо причина не использовать отсортированную функцию? sort() определяется только в списках, но sorted() работает с любыми итерациями и работает так, как вы ожидаете. Подробнее о сортировке см. эту статью.

Кроме того, поскольку внутренне он использует timsort, он очень эффективен, если вам нужно отсортировать по ключу 1, затем сортируйте по ключу 2.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *