簡體   English   中英

如何在python中將多個arrays輸入到同一個function中?

[英]How to input multiple arrays into the same function in python?

在沒有寫出三個不同 arrays 的名稱的情況下,我想知道如何從 arrays 中獲取值並將它們輸入到我的 function 中,其中某些國家的數量將被計算在內。 謝謝您的幫助

euCount = 0
asCount = 0
amCount = 0
saCount = 0
afCount = 0

def countCities(array):
  global euCount
  global asCount
  global amCount
  global saCount
  global afCount
  
  for x in array[0]:
    eu = "-eu"
    if eu in x:
      euCount = euCount + 1
    return euCount
    
    asia = "-as"
    if asia in x:
      asCount = asCount + 1
    return asCount
    
    af = "-af"
    if af in x:
      afCount = afCount + 1
    return afCount
    
    am = "-am"
    if am in x:
      amCount = amCount + 1
    return amCount
    
    sa = "-sa"
    if sa in x:
      saCount = saCount + 1
    return saCount

cities1 = ["london-eu","bangkok-as", "madrid-eu"]

countCities(cities1)

cities2 = ["paris-eu","milan-eu", "madrid-eu", "budapest-eu"]

countCities(cities2)

cities3 = ["houston-am","milan-eu", "bogota-sa", "nairobi-af"]

countCities(cities3)

您需要在 function 中創建 3 個參數,例如

def countCities(array1,array2,array3):

使用此參數,您可以在 function 中訪問所有三個 arrays。

不要為此使用全局變量,因為我假設您希望結果僅與參數相對應,而不是在 function 的幾次調用中累積計數。

您可以使用字典。 讓 function 創建那個字典:不同的國家擴展是它的鍵,對應的值是計數。

然后從輸入列表中的每個字符串中提取擴展名,並使用它來識別要增加的計數(只需要一個循環)。

這是建議的代碼:

def countCities(array):
    counts = {
        "eu": 0, 
        "as": 0,
        "am": 0,
        "sa": 0,
        "af": 0
    }
  
    for x in array:
        ext = x.split("-")[-1]
        if ext in counts:
            counts[ext] += 1
    return counts

暫無
暫無

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

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