在Python中根据长度对字符串进行分类

时间:2014-11-15 15:55:17

标签: string list python-2.7

我给了n个不同的字符串。我必须根据列表形成不同的字符串列表。例如,给定字符串为this,that,is,am,are,i,j,则应生成四个列表,如:

s[1] = [i,j]
s[2] = [is,am]
s[3] = [are]
s[4] = [this,that]

这些列表必须可以通过索引轻松访问(在本例中为长度)

1 个答案:

答案 0 :(得分:0)

您可以使用defaultdict

from collections import defaultdict

words = ['this','that','is','am','are','i','j']

with_lengths = [(word, len(word)) for word in words]
output = defaultdict(list)
for k, v in with_lengths:
  output[v].append(k)

for key in output:
  print '%i -> %s' % (key, output[key])

输出:

1 -> ['i', 'j']
2 -> ['is', 'am']
3 -> ['are']
4 -> ['this', 'that']