I can stringify a list by saying map(str, numbers), because str() happens to be a function that I can map with. But I can’t capitalize a list in that way, because capitalize() is a method. Yes, you can: >>> map(str.capitalize, ['alpha', 'beta', 'gamma']) ['Alpha', 'Beta', 'Gamma']
Or, if you have a list that might be of mixed types that happen to have capitalize methods: >>> import operator >>> map(operator.methodcaller("capitalize"), your_list)
Ruby and Python: pivot points
31–34 of 34 posts
Re: Ruby and Python: pivot points
#32Earlier quoted context omitted.
You wouldn't use a named Ruby method for something like this. You'd typically use a Proc or block. [1,2,3].map{ |x| x * 2 } or if you wanted to reuse the block for other things transform = lambda { |x| x * 2 } [1,2,3].map(&transform)
Exactly, but there should be an easier syntax that declaring a lambda for each algorithm I want to map over.
Re: Ruby and Python: pivot points
#33Earlier quoted context omitted.
See the design FAQ here: http://docs.python.org/faq/design.html#why-is-join-a-string-... Admittedly, the join syntax is somewhat counter-intuitive and arguably ugly, but it does the job without defining new built-in functions or adding extra syntax. If you really can't stand the syntax, you can always do this: # old style way of joining strings import string string.join([1,2,3], ' ') or: str.join(' ', [1,2,3]) Of cou…
$ipython In [1]: x = [1,2,3] In [2]: y = [4,5,6] In [3]: x + y Out[3]: [1, 2, 3, 4, 5, 6] Why use 6 [join()] characters when you can use 1 :)
Re: Ruby and Python: pivot points
#34Earlier quoted context omitted.
It's not pretty, but you can do it: >>> sum([['a', 'b', 'c'], ['d', 'e', 'f']], []) ['a', 'b', 'c', 'd', 'e', 'f'] This makes use of the optional start argument and list add operator. However, Python's docs suggest using itertools.chain instead: http://docs.python.org/library/functions.html#sum >>> import itertools >>> [l for l in itertools.chain(*[['a', 'b', 'c'], ['d', 'e', 'f']])] ['a', 'b', 'c', 'd', 'e', 'f'] (O…
I may be missing something, but why isn't skipping your list comprehension maintaining the benefit of using a generator? >>> from itertools import chain >>> chain(*[['a', 'b', 'c'], ['d', 'e', 'f']])