【问题标题】:If/Else Statement and Lists Within Functions - Python 3.x函数中的 If/Else 语句和列表 - Python 3.x
【发布时间】:2016-03-11 17:21:00
【问题描述】:

所以我正在尝试设计两个函数,一个用于创建列表,另一个用于检查该列表中的某些参数。 check() 函数是查看price() 函数的随机生成列表中是否有任何元素>100,然后通知用户哪些元素需要记录。老实说,我不确定从哪里开始使用 check() 函数,希望有人能给点建议?

def price():
    priceList = [1,2,3,4,5,6,7,8,9,10]
    print ("Price of Item Sold:")
    for i in range (10):
        priceList[i] = random.uniform(1.0,1000.0)
        print("${:7.2f}".format(priceList[i]))
    print("\n")
    return priceList

我知道check() 功能已经过时了,但就像我说的那样,我不确定该去哪里。

def check(priceList):
    if priceList > 100
        print ("This item needs to be recorded")

感谢您的任何帮助!

【问题讨论】:

  • 是否需要检查priceList的所有元素是否都小于100?或者找出哪些元素大于 100?
  • checkthese = [p for p in priceList if p > 100]
  • 价格表中不需要有任何初始值。您可以将 price() 的第一行更改为 priceList = [],因为无论如何所有项目都会被随机值替换。

标签: python list function python-3.x if-statement


【解决方案1】:

这似乎是最好的方法。

def price():
    priceList = [1,2,3,4,5,6,7,8,9,10]
    print ("Price of Item Sold:")
    for i in range (10):
        priceList[i] = random.uniform(1.0,1000.0)
        print("${:7.2f}".format(priceList[i]))
    print("\n")
    return priceList

以及检查列表。

def check(): #Will go through the list and print out any values greater than 100
    plist = price()
    for p in plist:
        if p > 100:
            print("{} needs to be recorded".format(p)) 

【讨论】:

    【解决方案2】:

    最简单的解决方案是循环传递给检查函数的值。

    def check(priceList, maxprice=100):
        for price in priceList:
            if price > maxprice:
                print("{} is more than {}".format(price, maxprice)
                print ("This item needs to be recorded")
    

    如果您愿意,可以使用 price() 生成价目表并立即将其传递给 check()。

    check(price())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多