首先排序再次使用itertools.groupby
上長度:
>>> from itertools import groupby
>>> s = 'I like programming in python because it is very fun and simple'
>>> for _, g in groupby(sorted(s.split(), key=len), key=len):
print ' '.join(g)
...
I
in it is
fun and
like very
python simple
because
programming
你也可以Ø做到這一點使用dict
:
>>> d = {}
>>> for word in s.split():
d.setdefault(len(word), []).append(word)
...
現在d
包含:
>>> d
{1: ['I'], 2: ['in', 'it', 'is'], 3: ['fun', 'and'], 4: ['like', 'very'], 6: ['python', 'simple'], 7: ['because'], 11: ['programming']}
現在,我們需要遍歷排序鍵和獲取相關值:
>>> for _, v in sorted(d.items()):
print ' '.join(v)
...
I
in it is
fun and
like very
python simple
because
programming
如果你想忽略標點符號,那麼你可以使用str.strip
和string.punctuation
:
>>> from string import punctuation
>>> s = 'I like programming in python. Because it is very fun and simple.'
>>> sorted((word.strip(punctuation) for word in s.split()), key=len)
['I', 'in', 'it', 'is', 'fun', 'and', 'like', 'very', 'python', 'simple', 'Because', 'programming']
我會等待看看是否有人可以提供使用字典的答案。如果沒有,那麼我會接受你的答案。 – user3036519 2014-12-04 08:25:27
@ user3036519我的第二個答案是隻使用字典。 – 2014-12-04 08:26:56
你可以在sort(d.values())中使用第二種方法,如v_list:print''.join(v_list) – thiruvenkadam 2014-12-04 08:30:41