我已经做过了,但是时间太长了,我怎么能做一个简单得多的方法呢?提前谢谢
letter_a = all_words.count('a')
letter_b = all_words.count('b')
letter_c = all_words.count('c')
letter_d = all_words.count('d')
letter_e = all_words.count('e')
letter_f = all_words.count('f')
letter_g = all_words.count('g')
letter_h = all_words.count('h')
letter_i = all_words.count('i')
letter_j = all_words.count('j')
letter_k = all_words.count('k')
letter_l = all_words.count('l')
letter_m = all_words.count('m')
letter_n = all_words.count('n')
letter_o = all_words.count('o')
letter_p = all_words.count('p')
letter_q = all_words.count('q')
letter_r = all_words.count('r')
letter_s = all_words.count('s')
letter_t = all_words.count('t')
letter_u = all_words.count('u')
letter_v = all_words.count('v')
letter_w = all_words.count('w')
letter_x = all_words.count('x')
letter_y = all_words.count('y')
letter_z = all_words.count('z')
print("There is:\n"
"A:",letter_a,",\n"
"B:",letter_b,",\n"
"C:",letter_c,",\n"
"D:",letter_d,",\n"
"E:",letter_e,",\n"
"F:",letter_f,",\n"
"G:",letter_g,",\n"
"H:",letter_h,",\n"
"I:",letter_i,",\n"
"J:",letter_j,",\n"
"K:",letter_k,",\n"
"L:",letter_l,",\n"
"M:",letter_m,",\n"
"N:",letter_n,",\n"
"O:",letter_o,",\n"
"P:",letter_p,",\n"
"Q:",letter_q,",\n"
"R:",letter_r,",\n"
"S:",letter_s,",\n"
"T:",letter_t,",\n"
"U:",letter_u,",\n"
"V:",letter_v,",\n"
"W:",letter_w,",\n"
"X:",letter_x,",\n"
"Y:",letter_y,",\n"
"Z:",letter_z,
"\n")
当然,您可以将代码减少到几乎两行。但是,如果您不知道python语法,那么可读性可能是个问题
用于循环。for循环的一个示例,它将计算字母“a”和“b”:
答案是多种多样的——当然,当你第十次写出
letter_X = all_words.count('X')
时,你应该一直在想“也许for
循环可以让我从这件事中解脱出来?”它会:类似地:
dict
而不是大量的独立变量,用字母作为键,以计数作为值吗?”在但是,这里最简单的方法是使用^{} ,例如:
^{pr2}$这种方法只处理一次字符串,而不是对每个字母进行
count
。Counter
基本上是一个具有一些额外有用功能的字典。在另外,您还需要考虑大小写-
"A"
是否应计为"a"
,反之亦然,还是它们是分开的?在相关问题 更多 >
编程相关推荐