cho*_*on4 1 python duplicates python-3.x
我有一个清单:
nums = [1, 2, 3, 1, 5, 2, 7, 11]
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个函数,返回每个数字在列表中出现的次数.输出可能如下所示:
1 occurred 2 times
2 occurred 2 times
3 occurred 1 time
5 occurred 1 time
...
...
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止所尝试的: -
为列表中的每个元素创建字典
-Have嵌套循环遍历每个元素并针对每个其他元素进行检查 -
如果元素匹配,则将该元素添加到该元素的字典键中
问题:
每次循环时,它都会重新检测相同的元素.因此,无论某个元素有多少,而不是加1,它都会被n次幂提升
Enter integers between 1 and 100: 5 2 41 4 5 2 2 4
4 occurs 4 times
2 occurs 9 times
41 occurs 1 times
5 occurs 4 times
Run Code Online (Sandbox Code Playgroud)
码:
def main():
original_nums = input("Enter integers between 1 and 100: ")
nums = [i for i in original_nums.split()]
my_dict = {}
for i in nums:
my_dict[i] = 0
for i in nums:
for j in nums:
if i == j:
my_dict[i] += 1
for i in my_dict:
print(i,"occurs",my_dict[i],"times")
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
计数器就是您所需要的
>>> from collections import Counter
>>> Counter([1, 2, 3, 1, 5, 2, 7, 11])
Counter({1: 2, 2: 2, 3: 1, 5: 1, 7: 1, 11: 1})
Run Code Online (Sandbox Code Playgroud)
或者您可以像这样修复您的代码
def main():
original_nums = input("Enter integers between 1 and 100: ")
nums = [i for i in original_nums.split()]
my_dict = {}
for i in nums:
my_dict[i] = my_dict.get(i, 0) + 1
# or .setdefault(i, 0) instead of .get(i, 0)
# setdefault is generally faster
for i in my_dict:
print(i, 'occurs', my_dict[i], 'times')
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
运行:
Enter integers between 1 and 100: 5 5 5 5 1 2 3 3 3
1 occurs 1 times
2 occurs 1 times
3 occurs 3 times
5 occurs 4 times
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
285 次 |
| 最近记录: |