5 ms·
I came across this when I was first learning Python and it has always impressed me: from random import shuffle deck = ['%s of %s' % (number, suit) for
by RyanMcGreal 12y ago
I came across this when I was first learning Python and it has always impressed me:
from random import shuffle
deck = ['%s of %s' % (number, suit) for number in '2 3 4 5 6 7 8 9 10 Jack Queen King Ace'.split(' ') for suit in 'Hearts Clubs Diamonds Spades'.split(' ')]
shuffle(deck)
- ajuc 12y agoI never liked how people in Python use stringWithSpaces.split instead of a list. Just feels wrong somehow. But I've seen it many times so it's probably pythonic
- TuringTest 12y agoIt makes sense when all the values in the list are text. Avoids lots of ", "
- DaFranker 12y agoI do it entirely, exclusively, only, purely because it requires less punctuation typing. It returns a list anyway. The performance hit is virtually unnoticeable in almost every use case (unless this is a function taking in input strings formatted this way many times per second, but in that case you've got way worse to worry about first...).
- icebraining 12y agoI agree; what I usually do is type the string.split() version in a REPL (I keep one open permanently) and then copy-paste the result to the file. It avoids having to do a big change if you need to add a new item with spaces in it.
- omaranto 12y agoIt's like old Perl idiom where Python's 'ab cd ef'.split(), would be written as qw(ab cd ef), which probably looks nicer --'qw' stands for 'quote words', I think.
- RyanMcGreal 12y agoAs DaFranker points out, it's just easier to type than ('Hearts', 'Diamonds', 'Spades', 'Clubs') and has less opportunity for typos and syntax errors. If I was concerned about performance I would replace it with a tuple, but it was Good Enough for a quick example.
- ajuc 12y agoSorry, I realised I sounded negative. Nothing against you, it's just my private opinion. It's not about performance, but about one more incidental step when reading the code. Small cost, but it's there.
- emmelaich 12y agoOne reason I like it is that you're probably going to be reading in the possible values from a stream or arg or config file anyway. But you have a good point. YAGNI is YAGNI.
- RubyPinch 12y agoalso in the std library, https://docs.python.org/3/library/collections.html#collections.namedtuple https://docs.python.org/3/library/collections.html#collectio... field_names can take a single space separated string
- hasenj 12y agoI love this idiom. I also use it in Javascript.