gpt4 book ai didi

python - 查找列表中的重复元素

转载 作者:太空宇宙 更新时间:2023-11-04 06:55:38 25 4
gpt4 key购买 nike

我有一个列表:

nums = [1, 2, 3, 1, 5, 2, 7, 11]

我正在尝试创建一个函数,返回每个数字在列表中出现的次数。输出可能如下所示:

1 occurred 2 times
2 occurred 2 times
3 occurred 1 time
5 occurred 1 time
...
...

这是我到目前为止尝试过的:
-为列表中的每个元素创建字典
-让嵌套循环遍历每个元素并对照每个其他元素检查它
-如果元素匹配,则向该元素的字典键加一

问题:
每次循环时,它都会重新检测相同的元素。因此无论某元素有多少,不是加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

代码:

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()

最佳答案

Counter就是你需要的一切

>>> 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})

或者您可以像这样修复您的代码

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()

运行时:

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

关于python - 查找列表中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22442273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com