【问题标题】:categorizing string according to length in Python在Python中根据长度对字符串进行分类
【发布时间】:2014-11-15 15:55:16
【问题描述】:

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

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

这些列表必须易于通过其索引(在本例中为长度)访问

【问题讨论】:

  • 我已经初始化了一个字典,然后在从用户那里获取字符串时,我检查了字符串长度,然后将该字符串添加到 dic[string length] 列表中。
  • 哪方面不符合要求?

标签: string list python-2.7


【解决方案1】:

你可以使用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']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-04
    • 2018-02-23
    • 2013-11-05
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多