如何將一個字串按照26個字母歸類到一個0-25下標的字串中?Python語言求助。
比如:
"abcdefgaj"
陣列:a
a[0] = 2 (兩個a)
a[1] = 1 (一個b)
……
我嫌if太麻煩
uj5u.com熱心網友回復:
https://www.cnblogs.com/longyuu/p/9787512.htmluj5u.com熱心網友回復:
https://blog.csdn.net/qq_40674583/article/details/81591211?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param還有結合這個,可以完成
uj5u.com熱心網友回復:
暫時還沒想到不用if的寫法
input_str = input("請輸入: ")
a = ''
s_list = []
# 將所有元素放入到串列
for i in input_str:
s_list.append(i)
# 去重
s_set = set(s_list)
for i in range(97, 123):
# chr(97) -> a chr(122) -> z
if chr(i) in s_set:
a += f'{s_list.count(chr(i))}'
else:
a += '0'
print(a)
uj5u.com熱心網友回復:
來個不用if的,望指正:#確保輸入為小寫字母串,否則 index out of range
input_str = input('請輸入小寫字母串(無空格):')
s_list = list(input_str)
a = [0 for x in range(26)]
for x in s_list:
a[ord(x) - 97] += 1
print(a)
uj5u.com熱心網友回復:
from collection import Counterprint(Counter('abcdefgaj'))
手機敲的,先試試
uj5u.com熱心網友回復:
import string
import itertools as it
s = "abccdefgaj"
g = it.groupby(sorted(s))
d = {i:len(list(j)) for i, j in g}
s = {"a[{}]".format(i):d.get(j, 0) for i,j in enumerate(string.ascii_letters)}
print(s)
uj5u.com熱心網友回復:
利用內碼轉換就是了,都不需要這么麻煩A的內碼我記得是41H 也就是85
從85開始+1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/11782.html
