气象局网站建设方案爱站网是什么
字典 - Dictionary
- keys()
- values()
- items()
- get()
- 获取文件中指定字符的个数
- 进阶版:获取所有单词的频数
- 进阶版:获取所有字符的频数
函数 | 内容 |
---|---|
keys() | 输出字典中的所有键 |
values() | 输出字典中的所有值 |
items() | 以元组的形式输出键值对 |
get() | 获取字典中指定键的值 |
keys()
test = {'chuck':1, 'fred':42, 'jan':100}
print(test.keys())
if "chuck" in test.keys():print("true")
keys() 方法将字典 test 中所有的键输出;
输出结果为:
dict_keys(['chuck', 'fred', 'jan'])
true
values()
test = {'chuck':1, 'fred':42, 'jan':100}
print(test.values())
if 1 in test.values():print("true")
values() 方法将字典 test 中所有的值输出;
输出结果为:
dict_values([1, 42, 100])
true
items()
test = {'chuck':1, 'fred':42, 'jan':100}
print(test.items())
for k, v in test.items():print("key =", k, "while values =", v)
items() 方法将字典 test 中的键值对输出;
输出结果为:
dict_items([('chuck', 1), ('fred', 42), ('jan', 100)])
key = chuck while values = 1
key = fred while values = 42
key = jan while values = 100
get()
inventory = {"apples":430, "banana":312, "pears":223, "oranges":221}print(inventory["banana"])
print(inventory.get("banana"))
print(inventory.get("banana",0))
get() 方法获取字典中指定键的值;
上述三种获取方法结果相同,而最后一种在找不到指定键的时候不会报错退出,而是会输出指定值,在这里是 0
获取文件中指定字符的个数
方法一:统计单个元素的个数
f = open('scarlet.txt', 'r')
txt = f.read()t_count = 0
for c in txt:if c == 't':t_count = t_count + 1
print("t: " + str(t_count) + " occurrences")
方法二:统计多个元素的个数
f = open('scarlet.txt', 'r')
txt = f.read()letter_counts = {}
letter_counts['t'] = 0
letter_counts['s'] = 0
for c in txt:if c == 't':letter_counts[c] = letter_counts[c] + 1elif c == 's':letter_counts[c] = letter_counts[c] + 1print("t: " + str(letter_counts['t']) + " occurrences")
print("s: " + str(letter_counts['s']) + " occurrences")
方法三:统计所有元素的个数
f = open('scarlet.txt', 'r')
txt = f.read()letter_counts = {}
for c in txt:if c not in letter_counts:letter_counts[c] = 0letter_counts[c] = letter_counts[c] + 1print("t: " + str(letter_counts['t']) + " occurrences")
print("s: " + str(letter_counts['s']) + " occurrences")
进阶版:获取所有单词的频数
word_counts = {}for word in sentence.split():word_counts[word] = word_counts.get(word, 0) + 1
进阶版:获取所有字符的频数
char_d = {}
for c in stri:char_d[c] = char_d.get(c, 0) + 1