提问人:Mohamed Ouni 提问时间:11/14/2023 最后编辑:Tom KarzesMohamed Ouni 更新时间:11/15/2023 访问量:55
在下面的程序中,我不明白数据是如何从列表中存储到count_dict
in the below program, i don't understand how was the data stored from the list into the count_dict
问:
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
print("Original list ", sample_list)
count_dict = dict()
for item in sample_list:
if item in count_dict:
count_dict[item] += 1 # how was the data stored into the variable count_dict?
else:
count_dict[item] = 1
print("Printing count of each item ", count_dict)
我只是不明白该程序是如何工作的
答:
1赞
Alex
11/14/2023
#1
如果 number 不在字典中,则程序创建值为 的键 ()。如果相同的数字再次出现在循环中,并且 dict 已经有此键,则此键的值将增加 。number
1
1
结果,其中键是数字,值是键的计数。count_dict
sample_list
sample_list
如果sample_list = [1, 1, 1]
然后count_dict = {1: 3}
例如,出现 2 次,则等于 。11
sample_list
count_dict[11]
2
更新
在 python 中为 dict 的键赋值的语法:dict[key] = value
它就像常规列表一样,但在列表中你有现成的键,这是列表中元素的顺序:
sample_list = ["a", "b"]
print(sample_list[0])
# >>> a
# changing value
sample_list[0] = "c"
print(sample_list[0])
# >>> c
与 dict 相同,但您应该自己定义 key
# Empty dict
example = {}
# Creating in dict key 99 with value 1
example[99] = 1
print(example[99])
# >>> 1
# Same as example[99] += 1
example[99] = example[99] + 1
print(example[99])
# >>> 2
print(example)
# >>> {99: 2}
# There is only one time with key 99 and value 2
# If i will use key that not in dict:
example[10]
# >>> KeyError: 10
# Because there is no item with key 10
评论
0赞
Mohamed Ouni
11/14/2023
因此,计算机知道他必须将这些数据存储为键或其他值
0赞
Mohamed Ouni
11/14/2023
我只是理解了那部分,我不明白字典中键和值的存储是如何工作的。无论如何,谢谢你的帮助,伙计
0赞
Alex
11/15/2023
@MohamedOuni dict: 的语法: .dict[key] = value
评论