簡體   English   中英

如何從用戶輸入中讀取多個(可變長度)參數並將其存儲在變量中並將其傳遞給函數

[英]How can I read multiple (variable length) arguments from user input and store in variables and pass it to functions

試圖創建一個計算器,它可以采用由空格分隔的可變長度的整數。 我能夠創建一個基本的計算器,它可以讀取兩個參數並執行操作。 以下是我正在努力實現的目標。

select operation: Add
Enter nos: 1 65 12 (this length can increase and any variable lenght of integers can be given)

我不確定如何將這個可變長度的 int 傳遞給函數,假設加法函數。 我可以為兩個變量做到這一點。

添加我所知道的:

x = input("enter operation to perform")
a = input("1st no.")
b = input("2nd no.")
def add(a,b):
    return a+b
if x == 1:
    print add(a,b)

不知道如何將多個從輸入讀取的參數傳遞給函數。

使用輸入可以實現:

>>> result = input("enter your numbers ")
enter your numbers 4 5
>>> result
'4 5'
>>> a, b = result.split()
>>> a
'4'
>>> b
'5'
>>> int(a) + int(b)
9

split方法將默認在空間上拆分您的字符串並創建這些項目的列表。

現在,如果你有更復雜的東西,比如:

>>> result = input("enter your numbers ")
enter your numbers 4 5 6 7 8 3 4 5
>>> result
'4 5 6 7 8 3 4 5'
>>> numbers = result.split()
>>> numbers
['4', '5', '6', '7', '8', '3', '4', '5']
>>> numbers = list(map(int, numbers))
>>> numbers
[4, 5, 6, 7, 8, 3, 4, 5]
>>> def add(numbers):
...  return sum(numbers)
...
>>> add(numbers)
42

正如您所看到的,您正在使用由空格分割的更長的數字序列。 當你調用split時,你會看到你有一個數字列表,但表示為字符串。 你需要有整數。 因此,這就是調用map以將字符串鍵入為整數的地方。 由於 map 返回一個 map 對象,我們需要一個列表(因此調用 list 周圍的地圖)。 現在我們有一個整數列表,我們新創建的add函數接受一個數字列表,我們只需對其調用sum

如果我們想要一些需要更多工作的東西,比如減法,就像建議的那樣。 讓我們假設我們已經有了我們的數字列表,為了讓示例看起來更小:

此外,為了使其更具可讀性,我將逐步進行:

>>> def sub(numbers):
...  res = 0
...  for n in numbers:
...   res -= n
...  return res
...
>>> sub([1, 2, 3, 4, 5, 6, 7])
-28

如果您使用 *args,它可以采用任意數量的位置參數。 您可以對其他操作進行類似的程序。

def addition(*args):
    return sum(args)

calc = {
        '+':addition,
        #'-':subtraction,
        #'/':division,
        #'*':multiplication,
        }

def get_input():
    print('Please enter numbers with a space seperation...')
    values = input()
    listOfValues = [int(x) for x in values.split()]
    return listOfValues


val_list = get_input()

print(calc['+'](*val_list))

這就是我實現計算器的方式。 有一個保存操作的字典(我會使用 lambdas),然后您可以將數字列表傳遞給字典中的特定操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM