【问题标题】:How to find min and max value from a list that is passed on to a function as argument? I want to find min and max of list but not getting the output如何从作为参数传递给函数的列表中找到最小值和最大值?我想找到列表的最小值和最大值,但没有得到输出
【发布时间】:2021-05-17 18:12:09
【问题描述】:

*#查找最大和最小标记的函数 #从一个列表输入,然后作为参数传递给函数 *

def marks(*args):
    print(args)
    print(max(args))
    print(min(args))

#marks input
mymarks = list(map(int,input("Enter the marks of all subjects: ").split()))
**#function call**
marks(mymarks)

Output:
Enter the marks of all subjects: 67 77 89 56 40
([67, 77, 89, 56, 40],)
[67, 77, 89, 56, 40]
[67, 77, 89, 56, 40]

【问题讨论】:

  • 您希望用户手动输入列表吗?还是作为列表参数输入?
  • 我希望用户手动输入,然后代码会自动将输入转换成列表。
  • 你知道*args 是做什么的吗?这意味着所有位置参数都将作为单个元组传入,然后您需要对其进行解包。在您的情况下,它将是一个包含单个数字列表的元组。简单的解决方法是删除*args,并接受一个列表参数,例如numbers
  • 当函数接受 n 个参数时,您传递了 1 个类型为列表的参数。需要解压marks(*mymarks)等列表或将方法改为def marks(arg)

标签: python list function dictionary max


【解决方案1】:

不要使用*args,而是声明像def marks(m) 这样的变量或使用args[0]

声明变量将是最好的,因为您可以使用max(m) 来获取列表中的最大值。

你的函数设置了最大的参数,这是一个元组。您的列表在该元组内。

编码愉快。

【讨论】:

    【解决方案2】:

    你快到了,但是你让mymarks的输入比需要的更复杂。

    不要使用*args,只需使用普通参数即可。而不是map,只需在输入值上调用split()split 已经返回了一个列表。

    def marks(args):
        print(args)
        print(max(args))
        print(min(args))
    
    
    # marks input
    mymarks = input("Enter the marks of all subjects: ").split()
    marks(mymarks)
    

    【讨论】:

      猜你喜欢
      • 2020-12-02
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 2020-03-08
      相关资源
      最近更新 更多