How to slice a list of objects into an object attribute association
I have a list of fixtures. Each lamp has a home club and country club attribute. I want to slice the list in association with his home club and away club. The sliced list should consist of homeclub items and dropdown items.
The easiest way to do this is to slice the luminaire list first. Then create a new list of matching Home and Away Clubs. I wanted to know if we can get it one step.
+2
a source to share
3 answers
It's not very clear what you are trying to do, but this code will take the first five fixtures and return a list of tuples, each containing the source and distant value of the corresponding object:
result = [(i.home, i.away) for i in fixtures[:5]]
This will split the two into two lists:
homes = [i.home for i in fixtures[:5]]
aways = [i.away for i in fixtures[:5]]
Or in one line:
homes, aways = [i.home for i in fixtures[:5]], [i.away for i in fixtures[:5]]
+3
a source to share
Of course, with a little work:
def split(fixture):
home, away = [], []
for i, f in enumerate(fixture):
if i >= 5:
home.append(f.home)
away.append(f.away)
return home, away
Or:
home, away = zip(*itertools.imap(operator.attrgetter('home', 'away'),
itertools.islice(fixture, 5, None)))
0
a source to share