Split a list into sub-lists based on attribute value

I have an array of objects that has an attribute suit, and I want to split into auxiliary arrays, based on which the object fits. I am currently using this:

    for c in cards:
        if c.suit.value == 0:
            spades.append(c)
        elif c.suit.value == 1:
            diamonds.append(c)
        elif c.suit.value == 2:
            clubs.append(c)
        else:
            hearts.append(c)

I tried using itertools.groupbyas follows:

suits = [list(g) for g in intertools.groupby(cards, lambda x: x.suit.value)]

But it just gives:

[[3, <itertools._grouper object at 0x000000000296B2E8>], ...]

My first approach works, I just think that there is a simple pythonic liner that does what I need.

+4
source share
3 answers

Although this is not a single-line font using a list, we make it more elegant:

spades, diamonds, clubs, hearts = collcard = [[] for _ in range(4)]

for c in cards:
    collcard[c.suit.value].append(c)

Here, we thus initialize the list with four empty subscribers, then add the map cto the list with the index c.suit.value.

, spades, - diamonds ..

, ( O (n log n)). , O (n) (, - O (1)).

, oneliners , , oneliners .

+4

, itertools.groupby tuple : ( ).

tuple list, .

(, _, , ) :

[list(g) for _,g in itertools.groupby(cards, lambda x: x.suit.value)]

, , sorted(cards) groupby ( - , ). , collections.defaultdict dict , , :

import collections

cards = collections.defaultdict(list)
colors = ["spades","diamonds","clubs","hearts"]

for c in cards:
    cards[colors[c.suit.value]].append(c)
+4

, - , , 40 :

allcards = sorted(cards, key=lambda x: x.suit.value)
spades, diamonds, clubs, hearts =  map(lambda x: allcards[x:x+10], range(0,40,10))

, . , .

+1

Source: https://habr.com/ru/post/1693209/


All Articles