Python sorted by len

Sorting strings by length — functional Python

While correct, this doesn’t look very elegant to me, or maybe it’s just my non-pythonic eye. Is this pythonic code? How would you write it? Maybe an imperative style is more appropriate?

5 Answers 5

data = ["something", "something else", "blah", "a string"] result = [(x, len(x)) for x in sorted(data, key = len)] 

Basically, its more straightforward to sort first then decorate. Although, I’m not sure why you would need the length of the list in your tuple. If you don’t really need it sorting by length can be much shorter.

If all I wanted was to output the data, I’d do it like this:

for string in sorted(data, key = len): print string, len(string) 

If you really wanted to eliminate the two references to len you could do:

mykey = len for string in sorted(data, key = mykey): print string, mykey(string) 

But unless you are reusing the code with different mykey’s that doesn’t seem worthwhile.

\$\begingroup\$ @Mauricio Scheffer, so you are just printing this list out? Why do you need the string lengths in there? \$\endgroup\$

\$\begingroup\$ Nitpicking: the space between the = when using keyword arguments is not PEP8 compliant. \$\endgroup\$

I don’t think that your solution looks bad. I would probably use a temporary variable to make the line length a bit more readable. You could consider itemgetter from the operator module.

from operator import itemgetter orig_list = ["something", "something else", "blah", "a string"] mylist = [(p, len(p)) for p in orig_list] mylist.sort(itemgetter(1)) 

Personally I think that this is just as readable.

mylist = sorted([(p, len(p)) for p in orig_list], key=itemgetter(1)) 

If you don’t want to call len twice for each item (if, for example, you need to call some expensive function instead of len ), you can sort by the second item without lambdas by using itemgetter .

from operator import itemgetter data = ["something", "something else", "blah", "a string"] l = [(s, len(s)) for s in data] l.sort(key = itemgetter(1)) 

However, if the order of members is not important, it would be better to place the length first in the tuple, because the default behaviour for sorting tuples is to compare the elements in order.

data = ["something", "something else", "blah", "a string"] l = sorted((len(s), s) for s in data) 

You can then switch them around during output if you want:

for length, item in l: print item, length 

Here’s another option. For the key function, it specifies a lambda that takes a two-item sequence, and unpacks the two items into «s» and «l», and returns «l». This avoids poking around each (string, length) pair by magic number, and also enforces a bit of a type constraint on the items to sort. Also, it breaks lines in convenient places, which is perfectly legal in Python:

sorted([(p, len(p)) for p in ("something", "something else", "blah", "a string")], key=lambda (s, l): l) 

And here is a version that uses a generator comprehension instead of a list comprehension. Generator expressions are evaluated as items are pulled from them, rather than all at once. In this example there’s no advantage, but when using expressions where items are expensive to create, or where iteration could terminate early (like database queries), generators are a big win:

sorted(((p, len(p)) for p in ("something", "something else", "blah", "a string")), key=lambda (s, l): l) 

And this version deterministically handles cases where there is some ambiguity on sorting only by length:

sorted(((p, len(p)) for p in ("something", "something else", "four things", "five things", "a string")), key=lambda (s, l): (l, s)) 

Источник

Читайте также:  Writing large file java

Возможности и примеры функции sorted в Python

Функция sorted() возвращает новый отсортированный список итерируемого объекта (списка, словаря, кортежа). По умолчанию она сортирует его по возрастанию.

Сортировка строк осуществляется по ASCII-значениям.

  • Возвращаемое значение — List (список).
  • Синтаксис: sorted(iterable,key=None,reverse=False) .
  • iterable : строка, список, кортеж, множество, словарь
  • key (необязательный параметр): если указать ключ, то сортировка будет выполнена по функции этого ключа.
  • reverse (необязательный параметр): по умолчанию сортировка выполняется по возрастанию. Если указать reverse=True , то можно отсортировать по убыванию.
 
# Сортировка строки
s2="hello"
print(sorted(s2)) # Вывод:['e', 'h', 'l', 'l', 'o']
print(sorted(s2, reverse=True)) # Вывод:['o', 'l', 'l', 'h', 'e']

# Сортировка списка
l1=[1, 4, 5, 2, 456, 12]
print(sorted(l1)) # Вывод:[1, 2, 4, 5, 12, 456]
print(sorted(l1, reverse=True)) # Вывод:[456, 12, 5, 4, 2, 1]

# Сортировка кортежа
t1=(15, 3, 5, 7, 9, 11, 42)
print(sorted(t1)) # Вывод:[3, 5, 7, 9, 11, 15, 42]
print(sorted(t1, reverse=True)) # Вывод:[42, 15, 11, 9, 7, 5, 3]

# Сортировка списка кортежей
t2=[(1, 2), (11, 12), (0, 2), (3, 2)]
print(sorted(t2)) # Вывод:[(0, 2), (1, 2), (3, 2), (11, 12)]
print(sorted(t2, reverse=True)) # Вывод:[(11, 12), (3, 2), (1, 2), (0, 2)]

# Сортировка множества
s1=
print(sorted(s1)) # Вывод:[1, 2, 3, 4, 6, 8, 11, 32]
print(sorted(s1, reverse=True)) # Вывод:[32, 11, 8, 6, 4, 3, 2, 1]

# Сортировка словаря
d1=
# Вернется список отсортированных ключей
print(sorted(d1)) # Вывод:[1, 2, 3]

# Вернется список отсортированных значений
print(sorted(d1.values())) # Вывод:['blue', 'green', 'red']

# Вернется список кортежей (ключ, значение), отсортированный по ключам.
print(sorted(d1.items())) # Вывод:[(1, 'green'), (2, 'red'), (3, 'blue')]

# Сортировка словаря в обратном порядке
print(sorted(d1, reverse=True)) # Вывод:[3, 2, 1]
print(sorted(d1.values(), reverse=True)) # Вывод:['red', 'green', 'blue']
print(sorted(d1.items(), reverse=True)) # Вывод:[(3, 'blue'), (2, 'red'), (1, 'green')]

Параметр key

Итерируемый объект можно также отсортировать по функции, указанной в параметре key . Это может быть:

  • Встроенная функция,
  • Определенная пользователем функция,
  • Лямбда-функция,
  • itemgetter,
  • attrgetter.

1. Встроенная функция

len() — посчитает длину объекта. Если указать len в виде параметра key, то сортировка будет выполнена по длине.

 
# Сортировка словаря на основе функции len
l1 =
# Возвращает список ключей, отсортированных по функции len
print(sorted(l1, key=len))
# Вывод: ['red', 'apple', 'carrot']

# Возвращает список значений, отсортированных на основе функции len
print(sorted(l1.values(), key=len))
# Вывод: ['fruit', 'color', 'vegetable']

# Сортировка списка на основе функции len
l1 = ['blue', 'green', 'red', 'orange']
print(sorted(l1, key=len))
# Вывод: ['red', 'blue', 'green', 'orange']

abs() вернет абсолютно значение числа. Если задать abs для key , то сортировка будет основана на абсолютном значении.

 
# Сортировка списка по абсолютному значению
l1 = [1, -4, 5, -7, 9, 2]
print(sorted(l1, key=abs))
# Вывод: [1, 2, -4, 5, -7, 9]

str.lower() — конвертирует все символы в верхнем регистре в нижний регистр. В таком случае список будет отсортирован так, будто бы все символы в нижнем регистре.

 
s1 = "Hello How are you"

# Разбивает строку и сортирует по словам
print(sorted(s1.split()))
# Вывод: ['Hello', 'How', 'are', 'you']

# Разбивает строку и сортирует после применения str.lower ко всем элементам
print(sorted(s1.split(), key=str.lower))
# Вывод: ['are', 'Hello', 'How', 'you']

d1 =
# Возвращает список ключей, отсортированный по значениям
print(sorted(d1))
# Вывод: ['Banana', 'Pears', 'apple']

# Возвращает список ключей, отсортированный после применения str.lower ко всем элементам
print(sorted(d1, key=str.lower))
# Вывод: ['apple', 'Banana', 'Pears']

2. Пользовательские функции

Также можно указывать свои функции.

Пример №1: по умолчанию сортировка кортежа происходит по первому элементу в нем. Добавим функцию, которая будет возвращать второй элемент кортежа. Теперь и сортировка будет опираться на соответствующий элемент.

 
# напишем функцию для получения второго элемента
def sort_key(e):
return e[1]

l1 = [(1, 2, 3), (2, 1, 3), (11, 4, 2), (9, 1, 3)]
# По умолчанию сортировка выполняется по первому элементу
print(sorted(l1))
# Вывод: [(1, 2, 3), (2, 1, 3), (9, 1, 3), (11, 4, 2)]

# Сортировка по второму элементу с помощью функции sort_key
print(sorted(l1, key=sort_key))
# Вывод: [(2, 1, 3), (9, 1, 3), (1, 2, 3), (11, 4, 2)]

Пример №2: можно сортировать объекты класса с помощью функций. Вот как это происходит:

  • У класса Studen есть три атрибута: name , rollno , grade .
  • Создаются три объекта этого класса: s1 , s2 , s3 .
  • Создается список s4 , который содержит все три объекта.
  • Дальше происходит сортировка по этому списку.
  • Определенная функция ( sort_key ) возвращает атрибут rollno .
  • В функции sorted эта функция задана для параметра key .
  • Теперь sorted() возвращает список объектов Student , которые отсортированы по значению rollno .
 
class Student:
def __init__(self, name, rollno, grade):
self.name = name
self.rollno = rollno
self.grade = grade

def __repr__(self):
return f"--"

# Создание объектов
s1 = Student("Paul", 15, "second")
s2 = Student("Alex", 12, "fifth")
s3 = Student("Eva", 21, "first")
s4 = [s1, s2, s3]

# Сортировка списка объектов
# Создание функции, которая вернет rollno объекта
def sort_key(s):
return s.rollno

# сортировка списка объектов без ключевого параметра, вызывает TypeError
print(sorted(s4))
# Вывод: TypeError: '>' not supported between instances of 'Student' and 'Student'

# Сортировка списка объектов по атрибуту: rollno
s5 = sorted(s4, key=sort_key)
print(s5)
# Вывод: [Alex-12-fifth, Paul-15-second, Eva-21-first]

3. Лямбда-функция

Также в качестве ключа можно задать лямбда-функцию. Сортировка будет выполняться по ней.

Пример №1: сортировка списка объектов класса на основе лямбда-функции, переданной для параметра key .

Источник

Sort a list according to the Length of the Elements in Python program

We have a list of strings and our goal is to sort the list based on the length of strings in the list. We have to arrange the strings in ascending order according to their lengths. We can do this using our algorithms or Python built-in method sort() or function sorted() along with a key.

Let's take an example to see the output.

Input: strings = ["hafeez", "aslan", "honey", "appi"] Output: ["appi", "aslan", "honey", "hafeez"]

Let's write our program using sort(key) and sorted(key). Follow the below steps to achieve the desired output using a sorted(key) function.

Algorithm

1. Initialize the list of strings. 2. Sort the list by passing list and key to the sorted(list, key = len) function. We have to pass len as key for the sorted() function as we are sorting the list based on the length of the string. Store the resultant list in a variable. 3. Print the sorted list.

Example

## initializing the list of strings strings = ["hafeez", "aslan", "honey", "appi"] ## using sorted(key) function along with the key len sorted_list = list(sorted(strings, key = len)) ## printing the strings after sorting print(sorted_list)

Output

If you run the above program, you will get the following output.

Algorithm

1. Initialize the list of strings. 2. Sort the list by passing key to the sort(key = len) method of the list. We have to pass len as key for the sort() method as we are sorting the list based on the length of the string. sort() method will sort the list in place. So, we don't need to store it in new variable. 3. Print the list.

Example

## initializing the list of strings strings = ["hafeez", "aslan", "honey", "appi"] ## using sort(key) method to sort the list in place strings.sort(key = len) ## printing the strings after sorting print(strings)

Output

If you run the above program, you will get the following output.

Conclusion

If you have any doubts regarding the tutorial, mention them in the comment section.

Источник

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