【问题标题】:Getting the percentage of a variable in Python 3在 Python 3 中获取变量的百分比
【发布时间】:2017-09-28 11:19:09
【问题描述】:

我似乎无法弄清楚如何获得变量的百分比。这是确切的任务:

用 Python 编写一个程序,每行存储一个单词列表 文本文件,打印并计算长单词的数量,即单词 超过 10 个字符并表示 long 的百分比 单词,给定文本文件中的单词总数。

这是我的代码:

wordcount = 0
longwordcount = 0

for line in sys.stdin:
    line = line.rstrip()
    charnum = len(line)
    wordcount = wordcount + 1
    percentage = int(longwordcount // wordcount) * 100
    if charnum > 10:
         longwordcount = longwordcount + 1
         print(line)



print("There are {0} words in the word list that have more than 10 characters.\nThis is {1}% of the total number of words in the text file." 
.format(longwordcount, percentage))

【问题讨论】:

  • 统计字数。计算 long 个单词的数量(都在同一个循环中)。 最后,当你把所有的东西都数完后,计算百分比。
  • 对于初学者来说,sys.stdin 并不理想。最好定义路径,或使用sys.argv[1],并使用with open() as... 打开/读取。
  • int(longwordcount // wordcount) * 100 是 0 乘以 100,或 1 乘以 100。您可能是指 longwordcount * 100 // wordcount。你应该在最后计算它,而不是你去。
  • 我个人不会在这里使用//(见上面的cmets),但如果你真的想尝试这样的东西。 percentage = (100 * longwordcount) // wordcount
  • 啊,对,我可以用它!感谢您的帮助!

标签: python python-3.x


【解决方案1】:

使用除法运算符而不是地板除法运算符,而不是 int 类型转换。如果需要,您可以使用格式语句来限制位数。

百分比 = 长字数 / 字数 * 100

【讨论】:

    猜你喜欢
    • 2015-04-16
    • 2021-11-04
    • 1970-01-01
    • 2019-05-18
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2021-11-28
    相关资源
    最近更新 更多