简体   繁体   中英

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

Without writing out the names of the three different arrays, I was wondering how I could take the values from inside the arrays and input them into my function, where the number of countries in certain continents would be counted. Thanks for the help

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)

You need to create 3 parameters in your function like

def countCities(array1,array2,array3):

with this parameters you can reach all three arrays in your function.

Don't use global variables for this, as I assume you want the results to correspond to the argument only, not accumulating counts over several calls of your function.

You can use a dictionary. Have the function create that dictionary: the different country extensions are its keys, and the corresponding values are counts.

Then extract the extension from each of the strings in the input list, and use it to identify which count to increment (only one loop needed).

Here is the suggested code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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