Python World
My Python World is to a discussion about python and features of the Python language.
PyTrick
Trick:- 1
# Python's list slice syntax can be used without indices # for a few fun and useful things: # You can clear all elements from a list: >>> lst = [1, 2, 3, 4, 5] >>> del lst[:] >>> lst []
# You can replace all elements of a list # without creating a new list object: >>> a = lst >>> lst[:] = [7, 8, 9] >>> lst [7, 8, 9] >>> a [7, 8, 9] >>> a is lst True # You can also create a (shallow) copy of a list: >>> b = lst[:] >>> b [7, 8, 9] >>> b is lst False
Trick:- 2
# collections.Counter lets you find the most common
# elements in an iterable: >>> import collections >>> c = collections.Counter('helloworld') >>> c Counter({'l': 3, 'o': 2, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1}) >>> c.most_common(3) [('l', 3), ('o', 2), ('e', 1)]
Trick:- 3
# Check if all elements in a list are equal
# Pythonic ways of checking if all # items in a list are equal: >>> lst = ['a', 'a', 'a'] >>> len(set(lst)) == 1 True >>> all(x == lst[0] for x in lst) True >>> lst.count(lst[0]) == len(lst) True # I ordered those from "most Pythonic" to "least Pythonic" # and "least efficient" to "most efficient". # The len(set()) solution is idiomatic, but constructing # a set is less efficient memory and speed-wise.
Trick:- 4
# How to merge two dictionaries
# in Python 3.5+
>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 3, 'c': 4}
>>> z = {**x, **y}
>>> z
{'c': 4, 'a': 1, 'b': 3}
# In Python 2.x you could
# use this:
>>> z = dict(x, **y)
>>> z
{'a': 1, 'c': 4, 'b': 3}
# In these examples, Python merges dictionary keys
# in the order listed in the expression, overwriting
# duplicates from left to right.
#
# See: https://www.youtube.com/watch? v=Duexw08KaC8
Trick:- 5
# How to sort a Python dict by value
# (== get a representation sorted by value)
>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
>>> sorted(xs.items(), key=lambda x: x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
# Or:
>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
No comments:
Post a Comment