Найти - Пользователи
Полная версия: Сортировка слов в списке относительно длинны
Начало » Python для новичков » Сортировка слов в списке относительно длинны
1
rafull6
Добрый день! Возникла проблема с сортировкой слов в списке относительно их длинны.
Вот мой код:
list1 = ['orange', 'apple', 'banana', 'carrot', 'potato', 'lettuce', 'milk', 'sugar', 'butter', 'flavour']
list1.sort(key=lambda word: len(word))
for i in list4:
    print len(i)
print(list1)
сама сортировка работает. на выходе получаю:
['milk', 'apple', 'sugar', 'orange', 'banana', 'carrot', 'potato', 'butter', 'lettuce', 'flavour']

но вот ответ нужно получить в таком виде:
4: ('milk',),
5: ('apple', ‘flour’, ‘sugar’),
6: ('orange', ‘banana’, ‘carrot’, ‘potato’, ‘butter’),
7: ('lettuce',)


то есть перед строкой со словами стоит число которое показывает сколько букв в этих словах.\

подскажите как это сделать пожалуйста
FishHook
#!/usr/bin/env python
# -* coding: utf-8 -*-
from itertools import groupby
list1 = ['orange', 'apple', 'banana', 'carrot', 'potato', 'lettuce', 'milk', 'sugar', 'butter', 'flavour']
list1.sort(key=lambda word: len(word))
print [list(x[1]) for x in groupby(list1, key=lambda x: len(x))]
py.user.next
>>> import itertools
>>> 
>>> lst = ['orange', 'apple', 'banana',
...        'carrot', 'potato', 'lettuce',
...        'milk', 'sugar', 'butter',
...        'flour']
>>> 
>>> lst.sort(key=lambda i: len(i))
>>> d = {n: tuple(g) for n, g in itertools.groupby(lst, len)}
>>> d
{4: ('milk',), 5: ('apple', 'sugar', 'flour'), 6: ('orange', 'banana', 'carrot', 'potato', 'butter'), 7: ('lettuce',)}
>>>
codersed
line = ['milk', 'apple', 'sugar', 'orange', 'banana', 'carrot', 'potato', 'butter', 'lettuce', 'flavour']
sort_line = sorted(line, key=len)
for count in sort_line:
    print(len(count), count)
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB