0

这是我的旧列表代码:

from collections import defaultdict

hello = ["hello","hi","hello","hello"]

def test2(strList):
    d = defaultdict(int)
    for k in strList:
        d[k] += 1
    print('<table>')
    for i in d.items():
        print('<tr><td>{0[0]}</td><td>{0[1]}</td></tr>'.format(i))
    print('</table>')

这是我的新清单:

hello2= ['bonjour','kiss']

预期输出:

<table>
<tr><td>hi</td><td>1</td><td>bonjour</td></tr>
<tr><td>hello</td><td>3</td><td>kiss</td></tr>
</table>
4

1 回答 1

2

我会在字典中键入键和值,然后有一个单独的输入列表,您可以从中计算键。

就像是:

keys = {"hello":{"postfix":"bonjour", "count":0}, 
        "hi":{"postfix":"kiss", "count":0}}

frequencies = ["hello","hi","hello","hello"]

for item in frequencies:
    keys[item]["count"] += 1

print('<table>')
for k,v in keys.items():
    print("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>"
          .format(k, v["count"], v["postfix"]))
print('</table>')

现在我做了你的功课...

于 2013-05-14T12:10:54.267 回答