views:

61

answers:

3

I have a list of fixtures.Each fixture has a home club and a away club attribute.I want to slice the list in association of its home club and away club.The sliced list should be of homeclub items and awayclub items.

Easier way to implement this is to first slice a list of fixtures.Then make a new list of the corresponding Home Clubs and Away Clubs.I wanted to know if we can do this one step.

A: 

Not quite the answer you were after, but (assuming [(home1, away1), (home2, away2), ...]) this is about as simple as you'll get.

homes = [h for h,a in fixtures]
aways = [a for h,a in fixtures]
Marcelo Cantos
+2  A: 

It's not very clear what you're trying to do, but this code will take the first five fixtures, and return a list of tuples, each of which contains a home and an away value of the respective object:

result = [(i.home, i.away) for i in fixtures[:5]]

This will separate the two into two lists:

homes = [i.home for i in fixtures[:5]]
aways = [i.away for i in fixtures[:5]]

Or on one line:

homes, aways = [i.home for i in fixtures[:5]], [i.away for i in fixtures[:5]]
Max Shawabkeh
Thanks for your reply.Exactly what I needed
gizgok
@gizgok: If that's exactly what you need, don't forget to Accept the answer (when the site gives you a chance). Spreads the karma!
Donal Fellows
@MaxI'm trying to do this:clubs=[c.home,c.away in fixtures[:5]] it's giving an error.Pardon my lack of knowledge of python,but can this be done again in one stmt if yes How
gizgok
@gizgok: You forgot the `for c` part: `clubs = [c.home, c.away for c in fixtures[:5]]`.
Max Shawabkeh
A: 

Sure, with a bit of 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)))
Ignacio Vazquez-Abrams
Yup does the job very well too
gizgok