Python 找出一个字符串出现3次的元素

方式一:利用字典中key唯一来判断

    存在时,计数统计给value,不存在时,赋值value为1

A = 'eddaabbcccdddd'
B = {}
for i in A:
if i in B: # 直接判断key在不在字典中
B[i] += 1
else:
B[i] = 1
new = sorted(B.items(), key=lambda B: B[1], reverse=True)
print(new)

 

方式二:

  用count去统计计数,把大于等于3的元素,放入一个新列表B中

A = 'aabbcccdddd'
B = []
def findkey():
    for i in A:
       count = A.count(i)   # 遍历统计,统计计数
       if count>=3 and i not in B:  # 统计大于等于3的元素,且不再B列表中
           B.append(i)
    return B

print(findkey())

 

posted @ 2023-07-02 11:09  hnfangh  阅读(42)  评论(0)    收藏  举报