當我嘗試計算給定字串中不同字符(大寫和小寫)的數量時,我得到一個空字典。
這是我嘗試過的代碼:在我輸入的 if 條件下variable a =1
,在 if 條件下什么也不做。
input_str = "AAaabbBBCC"
histogram = dict()
for idx in range(len(input_str)):
val = input_str[idx]
# print(val)
if val not in histogram:
# do nothing
a = 1
else:
histogram[val] = 1
print(histogram)
#print("number of different are :",len(histogram))
這是我的代碼輸出:
{}
我期待如下輸出:
{ 'A': 1,
'a': 1,
'b': 1,
'B': 1,
'C': 1
}
uj5u.com熱心網友回復:
如果你想計算字串中不同值的數量,你可以這樣做
input_str = "AAaabbBBCC"
histogram = dict()
for idx in range(len(input_str)):
val = input_str[idx]
if val not in histogram:
#add to dictionary
histogram[val] = 1
else:
#increase count
histogram[val] = 1
>>> histogram
{'A': 2, 'a': 2, 'b': 2, 'B': 2, 'C': 2}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/526854.html
標籤:Python字典if 语句