0
How to print out positions of males and females in a list of objects?
This is my attempt but i get [0,1,2] all the the time for both males and females https://code.sololearn.com/cIQd7mJ4yooq/?ref=app
7 Respuestas
+ 2
See altered code below for your function;
def print_sex():#prints out positions for males an
b = []
for i, p in enumerate(personList):
b.append((p.sex, i))
print('Positions for males: ',[a[1] for a in b if a[0].lower() =='male'])
print('Positions for females: ',[a[1] for a in b if a[0].lower() =='female'])
+ 2
Lenoname
The enumerate() function returns a tuple where the 1st element is an increasing integer (starts from 0 by default, matching an iterables index value) and the 2nd element is the current element from the passed in iterable (personList). So the first returned value is (0, personList[0]). The returned value is unpacked and it elements are placed into the corresponding variable names provided. In this case i, p. I used i to represent the current index value and p to represent the current person object at that index.
+ 2
It's basically 'unpacking', but it works pretty much the same as assigning multiple comma seperated variable names at the same time like;
a, b, c = 1, 2, 3
Or for instance the returned values from a function like the built-in divmod() which returns both the quotient and remainder from a number and a divisor. I.E. both results from a // b and a % b.
def divmod(num, div):
return a//b, a%b
quotient, remainder = divmod(13, 5)
Here quotient equals 2 and remainder equals 3.
+ 1
If you look at what I'm appending to the list b, you will see that it is a tuple of the sex for the current person and the current index. So you will have a list of tuples where the 0th element is that persons sex and the 1st element is the index that the person is in the personList. In the list comprehensions a is the current tuple element in the list b. So a[0] gets the sex of the person and a[1] gets that persons index in the personList.
0
ChaoticDawg
What is this kind of looping called? For i,p?could u explain a little what it is or give me the name of this type of looping or coding
0
Its probably in python core but does this method have a name?
0
ChaoticDawg what do a[0] and a[1] stand for?