【问题标题】:Is it possible to loop through several variables that have range values?是否可以遍历具有范围值的多个变量?
【发布时间】:2021-04-06 00:13:38
【问题描述】:

我正在101computin.net 上进行 python 挑战,但我不知道如何使我的代码更短。我曾尝试将这些变量放入list,但我无法检查密度是否在列表范围内,因为无法将对象解释为整数。

#Eureka! - Archimedes and King Hiero's Crown - www.101computing.net/eureka-and-king-hieros-crown/
mass = float(input("Input the mass of the crown in kg"))
volume = float(input("Input the volume of the crown in cubic meter"))

density = mass / volume

aluminum = range(2400, 2700)
bronze = range(8100, 8300)
silver = range(10400, 10600)
lead = range(11200, 11400)
gold = range(17100, 17500)
platinum = range(21000, 21500)

if density in Aluminum:
    print('Your crown is aluminum!')
elif density in bronze:
    print('B')
elif density in silver:
    print('S')
elif density in lead:
    print('L')
elif density in gold:
    print('G')
elif density in platinum:
    print('P')
else:
    print('Nope!')

显然,所有if/elif 语句都可以工作,但是有没有更简单的方法来循环遍历范围并根据密度确定输出是哪种金属?

【问题讨论】:

  • 您的黄金密度有误。应该在 19300 左右
  • @fdermishin 是的,我知道,我只是从我正在做的挑战中汲取了价值观......

标签: python list for-loop if-statement while-loop


【解决方案1】:

您可以使用dictionary

metals = {
    'aluminum': range(2400, 2700),
    'bronze': range(8100, 8300),
    'silver': range(10400, 10600)
}

for metal, values in metals.items():
    if density in values:
        print('Your crown is ' + metal + '!')
        break
else:
    print('Nope!')

【讨论】:

  • 当我运行这段代码时,我得到这个错误:NameError: name 'density' is not defined
【解决方案2】:

您可以使用字典在其中存储此范围。在下面的示例中,我构建了字典,其中键是产品名称,值是元组,其中第一个元素是实际范围,第二个元素是应该打印的消息:

mass = float(input("Input the mass of the crown in kg"))
volume = float(input("Input the volume of the crown in cubic meter"))

density = mass / volume

values = {
    'aluminium': (range(2400, 2700), 'Your crown is aluminum',
    'bronze': (range(8100, 8300), 'B'),
    'silver': (range(10400, 10600), 'S'),
    'lead': (range(11200, 11400), 'L'),
    'gold': (range(17100, 17500), 'G'),
    'platinium': (range(21000, 21500), 'P')
}


c = 0
for k,v in values.items():
    if density in v[0]:
        c += 1
        print(v[1])

if c > 0:
    print('Nope!')

【讨论】:

    【解决方案3】:

    它可能会更优化,但我会将金属及其密度范围放在字典中并对其进行迭代。

    metals = {"Aluminum":range(2400, 2700),"Bronze":range(8100, 8300),"Silver":range(10400, 10600),"Lead":range(11200, 11400),"Gold":range(17100, 17500),"Platinum":range(21000, 21500)}
    
    for metal,density in metals.items():
        if input_density in density:
            print(metal[0])
    

    【讨论】:

      【解决方案4】:

      您可以使用列表方法。我在处理 Unity 脚本时经常这样做。

      mass = float(input("Input the mass of the crown in kg"))
      volume = float(input("Input the volume of the crown in cubic meter"))
      
      density = mass / volume
      element_list = [range(2400,2700),range(8100,8300),range(10400,10600),range(11200,11400),range(17100,17500),range(21000,21500)]
      element_list2 = ["aluminum","bronze","silver","lead","gold","platinum"]
      for i in range(len(element_list)):
          if density in element_list[i]:
              print(f"Your crown made of: {element_list2[i]}")
      

      【讨论】:

        【解决方案5】:

        您可以使用字典来存储metals,同样for 循环之后的else 语句涵盖了未找到任何项目的情况。

        mass = float(input("Input the mass of the crown in kg "))
        volume = float(input("Input the volume of the crown in cubic meter "))
        
        metals = {
            'aluminum': range(2400, 2700),
            'bronze': range(8100, 8300),
            'silver': range(10400, 10600),
            'lead': range(11200, 11400),
            'gold': range(17100, 17500),
            'platinum': range(21000, 21500)
        }
        
        for metal, density in metals.items():
            if mass / volume in density:
                print(f'Your crown is {metal}!')
                break
        else:
            print('Nope!')
        

        输出(输入为24001):

        Input the mass of the crown in kg 2400
        Input the volume of the crown in cubic meter 1
        Your crown is aluminum!
        

        【讨论】:

        猜你喜欢
        • 2023-01-27
        • 2014-03-03
        • 1970-01-01
        • 1970-01-01
        • 2019-01-05
        • 1970-01-01
        • 1970-01-01
        • 2018-11-24
        • 1970-01-01
        相关资源
        最近更新 更多