As noob in python I struggle with a multidimensional array I have this part
def listMembers(Members):
for name in Names:
age=Ages[name]
print (name,age)
Names = ["John","William","Sarah"]
Ages = [22,33,44]
Members=[Names,Ages]
listMembers(Members)
And expect as result:
John, 22
Willem, 33
Sarah, 44
What must i change to get this?
-
You should really use a dictionary for this. Names will be keys, ages will be values.Idos– Idos2016年06月19日 09:25:05 +00:00Commented Jun 19, 2016 at 9:25
5 Answers 5
You can use enumerate to do the task...
def listMembers():
for i,name in enumerate(Names):
age=Ages[i]
print (name,age)
Output -
John 22
William 33
Sarah 44
But as said in the comments its better to use a dictionary here
Another way to do this is to use zip-
def listMembers():
for i,j in zip(Names, Ages):
print (i,j)
Edit :
As said in the comment you can do it without making direct references, as in real world, the function will be encapsulated within another class so you won't have direct access to data.-
def listMembers(Members):
names = Members[0]
ages = Members[1]
for i, j in zip(names, ages):
print (i, ", ", j)
2 Comments
Members argument, and is making hard-wired references to Names and Ages.You can use the zip built-in function:
Names = ["John", "William", "Sarah"]
Ages = [22, 33, 44]
for name, age in zip(Names, Ages):
print name, ',', age
Comments
You can use the the built-in function zip()
This will get you a list of tuples.
zipped = zip(Names, Ages)
tup_list = (list(zipped))
print (tup_list)
[('John', 22), ('William', 33), ('Sarah', 44)]
You can turn tup_list into a dictionary
dict(tup_list)
{'John': 22, 'Sarah': 44, 'William': 33}
Comments
The other answers show the cool in-built shortcuts in Python. However, IMHO you should really re-visit the basics the first and take the long route.
The following code uses basic functionality to create a list of integers ([0,1,2] in your case), which are iterated over to slice the arrays accordingly. This code assumes that names and ages has the same number of indexes.
def listMembers(Members):
names = Members[0] # slice off the first dimension
ages = Members[1] # slice off the first dimension
names_len = len(names) # get the length of names
for i in xrange(names_len): # xrange builds a list from 0 to given length.
print (names[i], ages[i]) # print off the second dimension
Names = ["John","William","Sarah"]
Ages = [22,33,44]
Members=[Names,Ages]
listMembers(Members)
Comments
Here's the solution you're looking for. It gets all the information it needs from the Members argument, which may cointain any number of lists. The list elements are grouped, converted to strings, joined with ", ", and printed. There are no global references to Names or Ages:
def listMembers(Members):
for t in zip(*Members):
print(", ".join(map(str, t)))
Names = ["John","William","Sarah"]
Ages = [22,33,44]
Members=[Names,Ages]
listMembers(Members)
Here's the output:
John, 22
William, 33
Sarah, 44