[Tutor] Python Idioms?

Steven D'Aprano steve at pearwood.info
Wed Apr 1 15:16:30 CEST 2015


On Wed, Apr 01, 2015 at 12:06:33PM +0100, Mark Lawrence wrote:

> In which case I'll stick with the more-itertools pairwise() function 
> which I pointed out on another thread just yesterday.  From 
> http://pythonhosted.org//more-itertools/api.html
> 
> <quote>
> Returns an iterator of paired items, overlapping, from the original
> 
> >>> take(4, pairwise(count()))
> [(0, 1), (1, 2), (2, 3), (3, 4)]

I betcha the implementation of pairwise is something really close to:

def pairwise(iterable):
    it = iter(iterable)
    return itertools.izip(it, it)

for Python 2, and for Python 3:

def pairwise(iterable):
    it = iter(iterable)
    return zip(it, it)



which is all well and good, but what if you want triplets, not pairs?

def threewise(iterable):
    it = iter(iterable)
    return zip(it, it, it)

I don't think it's very practical to include a *wise for every possible 
number of items...


Let's deal some cards!

import random
cards = []
for value in "A 2 3 4 5 6 7 8 9 10 J Q K".split():
    for suit in u"♠♣♦♥":
        cards.append(value + suit)

random.shuffle(cards)
deck = iter(cards)
hands = zip(*[deck]*8)
for name in "Groucho Chico Harpo Zeppo Gummo".split():
    print("%s gets dealt %s" % (name, ','.join(next(hands))))



I get these results, but being random of course you will get something 
different:

Groucho gets dealt 8♣,2♠,5♥,7♣,8♦,7♠,6♥,8♥
Chico gets dealt Q♦,K♦,3♥,7♦,K♠,J♠,9♥,10♥
Harpo gets dealt 10♣,4♦,4♥,A♠,A♦,K♥,3♠,J♥
Zeppo gets dealt 5♣,A♥,3♦,Q♣,9♣,9♠,4♣,2♥
Gummo gets dealt J♦,Q♠,4♠,10♦,J♣,6♦,5♦,A♣



-- 
Steve


More information about the Tutor mailing list