我對我擁有的字串有疑問。我的代碼是:
aminoacidos="IEKTENEVLDEKNSKLFSALLTGINRAFPFAQIPASVYEVHMETLFKITHSSNFNTSIQALVLINQVTVKAKLNSDRYYRTLYESLFDPRLVNSSKQGIYLNLLYKSLKQDALNVERVEA"
list_aminoacidos="DERKNHQSTAGVPLFYIMWC"
print("1. Repeated amino acids ", aminoacidos)
counts={i:0 for i in list_aminoacidos}
for amino in aminoacidos:
if amino in counts:
counts[amino] = 1
for k,v in counts.items():
print(k,v)
print("2. Max and min: ")
print(min(counts))
print(max(counts))
如您所見,它計算每個氨基酸的數量,但我不知道當我撰寫 min 和 max 命令時會發生什么,因為我得到 A 和 Y。但是,程式應該顯示 L 和 W,C。
先感謝您
uj5u.com熱心網友回復:
我相信你的最小值和最大值實際上是基于字典的鍵而不是這些鍵的值。因此,A 是最小值,因為它是最小值,因為 A<B..<Y。此外,Y 是最大值,因為 Y>X..>A。
我使用這種方法來獲得您想要的輸出。我想可以進一步完善。
print("2. Max and min: ")
min_keys = []
max_keys = []
min_value = min(counts.items(), key=lambda x: x[1])[1]
max_value = max(counts.items(), key=lambda x: x[1])[1]
for k, v in counts.items():
if v == min_value:
min_keys.append(k)
elif v == max_value:
max_keys.append(k)
print(min_keys)
print(max_keys)
uj5u.com熱心網友回復:
你看到這個結果是因為counts它是一個字典。當您不指定任何其他內容時,字典上的迭代會迭代鍵,而不是值。
標準庫中一個可以幫助您的有用類是collections.Counter:
from collections import Counter
counts = Counter(aminoacidos)
for item in counts.most_common():
print(item)
print(counts.most_common()[-1][0]) # Will print the key of the least common item
print(counts.most_common()[0][0]) # Will print the key of the most common item
uj5u.com熱心網友回復:
您的代碼給出了最小和最大字母,即 A 和 Y。嘗試:
print("2. Max and min: ")
max_dic={i:x for i, x in counts.items() if x == max(counts.values())}
min_dic={i:x for i, x in counts.items() if x == min(counts.values())}
print(max_dic)
print(min_dic)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426080.html
上一篇:如何在字串中移動(右)子字串?
