python程序中的逻辑错误

2024-03-29 14:25:26 发布

您现在位置:Python中文网/ 问答频道 /正文

alphabets ="abcdefghijklmnopqrstuvwxyz"
def calculation(text,alphabets):
    sample_list = []
    total_counter = 0
    for element in text:
        if element != " ":
            total_counter += 1
    total = total_counter

    for alphabet in alphabets:
        alphabet_counter = 0
        for element in text:
            if element == alphabet:
                alphabet_counter += 1
        tna = alphabet_counter
        percentage_counter = float((tna/total)*100)
        sample_list.append(percentage_counter)
    return sample_list

text = "sahib will be a very successful programmer one day."

x = calculation(text,alphabets)
print x

我试着做一个python程序员来计算文本中每个字符的百分比。但当我打印列表时,它会显示一个空列表


Tags: sampletextin列表forifcounterelement
3条回答

我把结尾改成:

x = calculation(text,alphabets)
for val in x:
    print("%5.2f"%val)

有一张单子是这样写的:

 9.30
 4.65
 4.65
 2.33
11.63
 2.33
 2.33

我可以建议你把这封信和百分比一起存起来会更有趣吗?尝试我的版本:

alphabets ="abcdefghijklmnopqrstuvwxyz"
def calculation(text,alphabets):
    sample_dict = {}
    total_counter = 0
    for element in text:
        if element != " ":
            total_counter += 1
    total = total_counter

    for alphabet in alphabets:
        alphabet_counter = 0
        for element in text:
            if element == alphabet:
                alphabet_counter += 1
        tna = alphabet_counter
        percentage_counter = float((tna/total)*100)
        sample_dict[alphabet]=(percentage_counter)
    return sample_dict

text = "the quack frown sox lumps oven the hazy fog"

x = calculation(text,alphabets)
for key,val in sorted(x.items()):
    print("%s"%key,"%5.2f"%val)

这将产生一个列表,开始于:

a  5.71
b  0.00
c  2.86
d  0.00
e  8.57
f  5.71
g  2.86
h  8.57
i  0.00

看看你怎么想。你知道吗

我认为这句话:

percentage_counter = float((tna/total)*100)

做整数运算会导致所谓的“楼层划分”结果混乱。 尝试替换为:

percentage_counter = 100*tna/float(total)

这并不是对您的问题的回答(因为user2464424已经回答了这个问题),而是对未来的一些提示。您的函数可以更简洁地表达为:

def calculation(text, alphabet):
    total = float(sum(ch in alphabet for ch in text))
    return [100 * sum(ch == letter for ch in text) / total for letter in alphabet]

这演示了Python的list comprehensiongenerator expressions,以及booleans are integers的事实。你知道吗

它还修复了程序中的一个错误,即字符总数仅排除空格,而不排除句点,而此版本排除了给定字母表中未显式显示的所有字符。(当前函数返回的列表总和不是100。)

相关问题 更多 >