这适用于从 1 到最大值的所有长度(如果列表中没有该长度的字符串,则某些列表将为空a
):
>>> a = ['a', 'b', 'ab', 'abc']
>>> m = max(len(x) for x in a)
>>> print [[x for x in a if len(x) == i + 1] for i in range(m)]
[['a', 'b'], ['ab'], ['abc']]
但是,如果您只想列出其中的长度,则a
必须使用set(len(i) for i in lst)
而不是范围。
>>> print [[x for x in a if len(x) == i] for i in set(len(k) for k in a)]
[['a', 'b'], ['ab'], ['abc']]
列表没有区别['a', 'b', 'ab', 'abc']
。但是如果你稍微改变一下,例如:[['a', 'b'], ['ab'], ['abcd']]
,你会看到不同之处:
>>> a = ['a', 'b', 'ab', 'abcd']
>>> print [[x for x in a if len(x) == i] for i in set(len(k) for k in a)]
[['a', 'b'], ['ab'], ['abcd']]
>>> print [[x for x in a if len(x) == i + 1] for i in range(max(len(x) for x in a))]
[['a', 'b'], ['ab'], [], ['abcd']]