使用Python 3计算列表(字符串)的长度直方图的最佳方法是什么?
程序将计算所有元素的长度,具有相同长度的组元素并返回每个组的大小,与该组中元素的长度配对。
对于以下输入列表:
lis = [ "this" , "is" , "what" , "i" , "have" , "to" , "do" ]
预期结果是:
Letters per word:
3 with 4 letters
3 with 2 letters
1 with 1 letters
是否有内置的容器或功能可以促进这个?
答案 0 :(得分:8)
while (true) {
client = sock.accept();
inFromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
cIn = inFromClient.readLine();
System.out.println("" + cln);
inFromClient.close() //add this
}
答案 1 :(得分:1)
您可以使用Counter
from collections计算可迭代的任何可清除值
>>> lis = [ "this" , "is" , "what" , "i" , "have" , "to" , "do" ]
>>> from collections import Counter
>>> count = Counter(len(x) for x in lis)
>>> for key in count:
print(count[key], 'with', key, 'letters')
1 with 1 letters
3 with 2 letters
3 with 4 letters
答案 2 :(得分:0)
我会使用 collections.defaultdict
:
import sys
import collections
def processData(data):
results = collections.defaultdict(list)
for word in data:
results[len(word)].append(word)
return results
if len(sys.argv) > 1:
data = sys.argv[1:]
print "Letters per word:\n"
for k,v in dict(processData(data)).iteritems():
print "{} with {} letters --> {}".format(len(v), k, ', '.join(v))
<强>输出:强>
➜ python test.py stack overflow rocks
Letters per word:
1 with 8 letters --> overflow
2 with 5 letters --> stack, rocks
答案 3 :(得分:0)
lis = [ "this" , "is" , "what" , "i" , "have" , "to" , "do" ]
a=[]
for item in lis:
a.append(len(item))
b=set(a)
print "Letters per words are :"
for item in b:
k=a.count(item)
print "%d with %d letters"%(k,item)