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

Time:08-14

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)

CodePudding user response:

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.

CodePudding user response:

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
  • Related