【问题标题】:Counting values in a Python array计算 Python 数组中的值
【发布时间】:2020-12-09 05:08:55
【问题描述】:

我非常接近解决这个问题,但我必须正视解决方案。该程序旨在接收以摄氏度为单位的温度值,将其转换为华氏度,然后计算“凉爽”、“温暖”和“炎热”天数。我已经弄清楚了这个问题的前两部分,但无论出于何种原因,我的程序都没有正确计算每种日子的数量。

temperature_list = []

value = int(input("Number of temperatures to enter: "))

for i in range(value):

    #We now collect the values

    t = int(input("Enter temperature: "))

    temperature_list.append(t)

print("Your entered temperatures in Celsius are: ", temperature_list)

#Next up is to print those temperatures in Fahrenheit, which we'll do in a batch
f_list = list()
f = [t*1.8 + 32 for t in temperature_list]
f_list.append(f)
fint = int(f[0])


cooldays = 0
hotdays = 0
for f in f_list:
    if fint > 65 :
        cooldays = cooldays + 1
    if fint < 80 :
        hotdays = hotdays + 1
print("Your temperature in Fahrenheit is: ", f[:])
warmdays = (len(f_list) - (cooldays + hotdays))
print(cooldays)
print(hotdays)
print(warmdays)

有人能告诉我我错过了什么吗?

【问题讨论】:

  • 当您可能应该使用 int(f) 时,您在循环中使用 fint 作为条件句
  • 您的逻辑还允许cooldayshotdays 在同一天发生,从而使您的暖日无效
  • 我认为您的 > 和
  • 您提到的计数不正确。你能告诉我们当前的输出和预期的输出吗?不要忘记告诉我们输入
  • Grand J,你说得对。我经常重做线条,以至于我忽略了检查标志的朝向!不过,用“f”替换“fint”给了我通常的“'

标签: python list sorting


【解决方案1】:

目前,您正在检查 fint 与每次迭代的阈值。相反,您想对照f_list 中的每个值检查它。

其次,根据您的要求,您可能还需要更改条件。比如 66 大于 65 也小于 80。所以它会增加两者...请修改你的条件。

第三,f = [t*1.8 + 32 for t in temperature_list] 使f 成为浮动列表。您将此附加到另一个列表f_list。本质上,您的 f_list 现在是一个 2D 矩阵。例如:[[65,66,68.2, 98.3]] 注意双方括号... 您可以直接将温度分配给f_list,而不是创建中间变量f

f_list = [t*1.8 + 32 for t in temperature_list]
for f in f_list:
    if f < 65 :
        cooldays = cooldays + 1
    elif f > 80 :
        hotdays = hotdays + 1

【讨论】:

  • 这与问题有何不同?
  • 啊,我没有立即注意到 int 部分被删除
  • 为什么改成&gt;= 65 and &lt; 80?之前很好,因为它是两个 if 而不是 if elif。我认为前一个更符合 OPs 问题,因为我们不知道预期的值是什么
  • 我认为我们需要 OPs 的意见才能更清楚。请注意,OP 将 fint 转换为 int。
  • 这解决了!我需要扭转一些标志,但删除 2D 矩阵并仅使用这些值就像一个魅力!非常感谢。
猜你喜欢
  • 2017-12-23
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
  • 1970-01-01
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多