基本上,我希望比較串列中字串的每個字符以及它重復的次數。我的方法是使用 for 或 while 回圈,但第一個問題是如果我比較索引會超出范圍i == i 1,第二個問題是即使這奇跡般有效,它也會再次比較索引中的每個字符太,所以它會打擾我的計數。我想檢查每個字符在串列中的出現次數是否相等或奇數,例如串列
list=["BACCUBAU"]中每個字符的出現次數是否相同
uj5u.com熱心網友回復:
這就是我認為OP正在尋找的東西:
from collections import Counter
list_of_strings = ['banana', 'apple', 'grapefruit']
for str_ in list_of_strings:
print(f'{str_}:')
for k, v in Counter(str_).items():
print('\t{} occurs {} time{}'.format(k, v, 's' if v > 1 else ''))
輸出:
banana:
b occurs 1 time
a occurs 3 times
n occurs 2 times
apple:
a occurs 1 time
p occurs 2 times
l occurs 1 time
e occurs 1 time
grapefruit:
g occurs 1 time
r occurs 2 times
a occurs 1 time
p occurs 1 time
e occurs 1 time
f occurs 1 time
u occurs 1 time
i occurs 1 time
t occurs 1 time
uj5u.com熱心網友回復:
解決您的問題的一種方法是:
- 獲取字串中的唯一字符
- 計算字串中每個字符出現的次數
給定字串:
my_str = "this is my string"
首先獲取唯一字符:
my_list_of_unique_characters = list(set(my_str))
現在遍歷您的串列并計算出現次數:
for character in my_list_of_unique_characters:
number_occurrences = my_str.count(character)
print("Occurrences of character " character " : " str(number_occurrences))
希望能幫助到你!
uj5u.com熱心網友回復:
好的,假設您有一個字串串列:
a = ["BBAACCDD","E"]
要查找串列中的每個事件,我建議使用collections.Counter模塊中collections的
class collections.Counter([iterable-or-mapping])
Counter 是用于計算可散列物件的 dict 子類。它是一個集合,其中元素存盤為字典鍵,它們的計數存盤為字典值。計數可以是任何整數值,包括零計數或負計數。Counter 類類似于其他語言中的 bag 或 multisets。
>>> joined_str = ''.join(a)
>>> occurences = cc.Counter(joined_str)
>>> occurences
Counter({'B': 2, 'A': 2, 'C': 2, 'D': 2, 'E': 1})
>>> #check with a filter if all occurences are even
>>> if all(filter(occurences.values(),lambda x:not x%2)):
... print("All even numbers of occurences")
... else:
... print("Not All even number of occurences")
Not All even number of occurences
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505440.html
標籤:Python python-3.x 细绳 列表 特点
