简体   繁体   English

如何在 python 的输入周围放置方括号?

[英]How do i put square parentheses around an input in python?

I'm new to python and my professor gave us the assignment to write different functions.我是 python 的新手,我的教授给了我们编写不同函数的任务。 Writing the function is easy but he gave us examples of what the output should be and it kind of threw me off.编写 function 很容易,但他给了我们 output 应该是什么的例子,这让我有点失望。

>>> average([])
0.0
>>> average([1.0])
1.0
>>> average([5.0, 10.0, 20.0])
11.666666666666666

This was the example.这就是例子。 How can I place square brackets around my input like that?我怎样才能像这样在我的输入周围放置方括号?

Square parenthesis in python signify that your function is taking in an list as one of it's arguments. python 中的方括号表示您的 function 正在将其列为 arguments 之一。

You would take multiple inputs and append them to a list, which later you would input in the function.您将获取多个输入并将 append 输入到一个列表中,稍后您将在 function 中输入该列表。

Therefore your code will look like this:因此,您的代码将如下所示:

def average(listOfNumbers):
    total = sum(listOfNumbers)
    return float(total)/len(listOfNumbers)

numOfInputs = int(input("Number of inputs: "))
numbers = []
for i in range(numOfInputs):
    numbers.append(int(input("Enter Number: ")))
print(average(numbers))

That means that your function has to take a list as an input.这意味着您的 function 必须将列表作为输入。 Therefore, you should assume your function is like below:因此,您应该假设您的 function 如下所示:

      def average(input): 
          # input looks like [0,5,6]

I hope this helps.我希望这有帮助。

def average(inputlist)
    return sum(inputlist)/len(inputlist)

If you do this如果你这样做

average([2, 4, 5])

The function will know you are passing a list parameter since python is a dynamically typed language, that is - the type of the parameter inputlist will be determined at runtime. function 将知道您正在传递一个列表参数,因为 python 是一种动态类型语言,也就是说 - 参数输入列表的类型将在运行时确定。

Alternatively, you could just define your list first, then pass it to the function like this.或者,您可以先定义您的列表,然后像这样将其传递给 function。

inputValues = [2, 4, 5]
average(inputValues) 

Create a list and then append your inputs to the list and then apply the function Try this code:创建一个列表,然后将 append 输入到列表中,然后应用 function 试试这个代码:

nums = []
n = int(input())
for i in range(n):
    nums.append(int(input()))
average(nums)

This above code will take an input n and then it takes n input numbers and then applies the average (any mathematical function).上面的代码将接受一个输入n ,然后接受n输入数字,然后应用平均值(任何数学函数)。

def average(*args):
    for i in args:
        return sum(i)/len(i)
    
print(average([42,67,23,89]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM