我有一个具有以下结构的字典:
count = 0 leng = 0 i = 0 for key1,key2 in range(1,len(bigrams)): count = count +1 leng = leng + (bigrams.get((key1,key2),0)) print(count) print(leng)
我想在字典中计算次数' key1'例如,显示为键元组中的第一个单词。
我开始编写下面提到的代码,但无法进一步思考:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title> Competition Organizer </title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<ul>
<li><a href="">Log Out</a></li>
<li><a>Notification</a></li>
<li><a href="Report.html">Generate Report</a></li>
<li><a href="Admin.html">Home</a></li>
<li style="float:left;color:white;">Competition Management</li>
</ul>
<form action="http://localhost/GCSweb/add.php" method="POST">
<div>
<br>
<br>
<br>
<label><b>Competition Name</b></label>
<input type="text" placeholder="Enter Competiton Name" name="compname" required>
<label><b>Competition Mentor</b></label>
<input type="text" placeholder="Enter Competiton Mentor Name" name="compmenname" required>
<label><b>Competiton Description</b></label>
<textarea rows="20" cols="50" name="compdescription" form="CompForm" placeholder="Enter Description Here..." required></textarea>
<br>
<input type="submit" value="Submit" name="submit">
</div>
</form>
</body>
</html>
有关我应该如何进行的任何建议?
答案 0 :(得分:1)
from collections import defaultdict
der = {('key1','key2'): 50, ('key3','key4'): 70, ('key1','key5'): 90}
b = defaultdict(int)
for item, ler in der:
b[item] += 1
print b ## defaultdict(int, {'key1': 2, 'key3': 1})
print b['key1'] ## [2]
答案 1 :(得分:0)
我使用带有生成器表达式的sum()
迭代键,依次测试每个键:
bigrams = {('key1','key2'): 50, ('key3','key4'): 70, ('key1','key5'): 90}
def number_of_times_key_appears_as_first_word(key, dictionary):
return sum(k[0] == key for k in dictionary)
assert number_of_times_key_appears_as_first_word('key1', bigrams) == 2
assert number_of_times_key_appears_as_first_word('key3', bigrams) == 1
assert number_of_times_key_appears_as_first_word('key2', bigrams) == 0
答案 2 :(得分:0)
您可以使用collections.Counter
计算密钥的每个部分,如下所示:
from collections import Counter
dic = {('key1','key2'): 50, ('key3','key4'): 70, ('key1','key5'): 90}
keys_0 = Counter(key[0] for key in dic.keys())
keys_1 = Counter(key[1] for key in dic.keys())
# keys_0 = Counter({'key1': 2, 'key3': 1})
# keys_1 = Counter({'key2': 1, 'key4': 1, 'key5': 1})
如果需要,可以使用dict(Counter(...))
答案 3 :(得分:0)
下面给出了所需的计数:
dict1 = {('key1','key2'): 50, ('key3','key4'): 70, ('key1','key5'): 90, ('key3','key1'): 90}
count = 0
for keys in dict1.keys():
if 'key1' in keys:
if (keys[0] == 'key1'):
count = count + 1
print count