How to show a dictionary sorted on a value within its data?
Steven D'Aprano
steve at pearwood.info
Fri Oct 3 03:55:36 EDT 2014
On Fri, 03 Oct 2014 12:44:32 +1000, Chris Angelico wrote:
> On Fri, Oct 3, 2014 at 9:16 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>>> Anyway, pylint doesn't complain about a bare use of lambda, but it
>>> does complain about a map applied to a lambda or a filter applied to a
>>> lambda. Pylint says they could be replaced by a list comprehension,
>>> with the warning "deprecated-lambda".
>>
>> The warning name is misleading, lambda is not deprecated. But
>> stylistically, many people prefer to use a generator expression in
>> place of map or filter:
>>
>> # instead of this
>> map(lambda x: 2*x+1, values)
>>
>> # use this
>> (2*x+1 for x in values)
>>
>> # instead of this
>> filter(lambda x: x > 23, values)
>>
>> # use this
>> (x for x in values if x > 23)
>
> Don't forget that your equivalencies are based on the Py3 map/filter,
Dan did ask about Python 3.x :-)
> which return non-list iterables. There's no really convenient equivalent
> to the map() usage of "call this function with each of these args, and
> discard the return values", as it looks very odd to do a list comp for
> nothing:
map doesn't discard the return values. It accumulates them in a list, or
yields them in a list comp.
> [print(x) for x in list_of_strings]
That would be an abuse of a list comprehension, generator expression or
map since it will produce a whole lot of None values. If you really want
to discard the return values, put them in a for-loop:
for s in list_of_strings:
print(s)
> Short of borrowing Pike's automap syntax:
>
> print(list_of_strings[*])
you mean something like this perhaps?
print(*list_of_strings, sep='\n')
> there's really not much that's better than the original map() call. On
> the other hand, there aren't actually all that many times when I've
> needed to do this, and the simple for loop generally suffices:
>
> for x in list_of_strings: print(x)
Exactly.
--
Steven
More information about the Python-list
mailing list