-
Notifications
You must be signed in to change notification settings - Fork 501
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
New tricks #1
Comments
Tuplestuple syntax
unpacking iterable of length 1
unpacking with starred expression
|
loop over dicts that share (some) keysdctA = {'a': 1, 'b': 2, 'c': 3}
dctB = {'b': 4, 'c': 5, 'd': 6}
for ky in set(dctA) & set(dctB):
print ky this one is much slower: for ky in dctA:
if ky in dctB:
print ky |
lookup deep nested value in dictsnested = {'a': {'b': {'c': {'d': 1}}}}
print nested.get('a', {}).get('b', {}).get('c', {}).get('d')
print nested.get('x', {}).get('y', {}).get('z', {}).get('0') This is almost just as fast as completly testing whether the variable exists and IMO more readable. |
Copy listsa = [1, 2, 3, 4, 5]
cpyA = list(a)
cpyB = a[:] cpyB is faster |
Startswithlst = range(10000)
def string_startswith():
for _ in lst:
'blasdfsf'.startswith('__')
'__aqqqqqqqqqqqqqqqqqsdfsf'.startswith('__')
def string_eq_first_two():
for _ in lst:
'blasdfsf'[:2] == '__'
'__aqqqqqqqqqqqqqqqqqsdfsf'[:2] == '__' The second one is faster |
Hey agumonkey, |
Hey obeleh, |
They sit between tricks and easy to overlook syntax. Here's another thing I only found recently: slice operator accepts None
|
@agumonkey print('aabbccddeeff'[0:]) For me this is more readable. |
It's unrelated, ability to pass a a value to [:] is rarely shown and very valuable. (see this example). |
Never seen this trick before so I played around a bit.
Is it possible to do something like the following (which doesn't work)?
|
@agumonkey |
@bash-j |
@brennerm |
The way to access nested dicts is like this: d = {'Jeff Smith': {'name': 'Jeff', 'age': {'years': 24, 'decades': 2.4}}}
"My name is {name} and I'm {age[decades]} decades old.".format(**d['Jeff Smith']) But I suppose he wants to use the corresponding 'years' and 'decade' string as well. |
Oh I see, accessing both key and value. I agree it's not a great idea. Better have ... 'age' : {'value' : 24, 'type' : 'years'} ... Anyway, I didn't remember the '{key[subkey]}' syntax. Tried it with 2 level nested dicts :
N level nested dicts works too : |
I thought that format would replace the {0} in age[{0}] with 'decades' first before attempting the dictionary look up. I found that chaining two format functions together works:
|
Trick for socket.recv
|
property cache with Descriptor
|
compound Boolean statements shortening trick:Requiring two (or more) objects both be in a given set required as many "object in set ?" Boolean statements coupled by an and, repeating the same set name for each object. The resulting compound Boolean statement can be long especially when there are many objects and/or the set being tested has a long name. if A in my_dictionary[key].adjacent_nodes and B in my_dictionary[key].adjacent_nodes:
do_stuff() I found that with python, you can easily eliminate all the redundant references to the same set in these compound Boolean statements: if A and B in my_dictionary[key].adjacent_nodes:
do_stuff() adding a check for another item in the same set would be just as easy, add minimal verbosity, and be more readable using the trick: if A and B and not C in my_dictionary[key].adjacent_nodes I basically tried it because trying code is so easy in python, and it worked, I was pleasantly surprised but this could easily be very common knowledge that I missed in my readings. Either way, thank you all for gathering this collection of tricks, many of which were new to me and their usefulness immediately apparent. |
A simple calculator created using
|
Funny, conditionalfunctional.py inspired writing the similar thing, albeit not interactive, more an assembler POV:
|
Using #! /usr/bin/env python3
"""set global variables from dict"""
d = {'a': 1, 'b': 'var2', 'c': [1, 2, 3]}
globals().update(d)
print(a, b, c) |
A simple way to remove duplicate items in a list. #! /usr/bin/env python3
"""remove duplicate items from list"""
items = [1, 2, 2, 3, 3, 3]
newitems = list(set(items))
print(newitems) |
merged your pull request and added you to the CONTRIBUTORS ;) |
@tutoringsteve |
Control white spaces in a string easily. #! /usr/bin/env python3
"""control the whitespaces in string"""
s = 'The Little Price'
# justify string to be at least width wide
# by adding whitespaces
width = 20
s1 = s.ljust(width)
s2 = s.rjust(width)
s3 = s.center(width)
print(s1) # 'The Little Price '
print(s2) # ' The Little Price'
print(s3) # ' The Little Price '
# strip whitespaces in two sides of string
print(s3.lstrip()) # 'The Little Price '
print(s3.rstrip()) # ' The Little Price'
print(s3.strip()) # 'The Little Price' |
@kzinglzy |
example for the property cache decriptor:
and the output will be:
which the func just compute once : )
|
@kzinglzy |
By the way, @brennerm , it's necessary to check @tutoringsteve 's code. It seems to be a mistake instead a trick. Because:
can not equal to be this !!!!!!!!!!
and in fact
which means it doesn't check so, when A is not empty, it's seems right. And when A is empty, it doesn't work. Here is a simple example.
|
@kzinglzy |
time to sleep, and there is a suggestion about the quality of I think there is too many simple code, which can't be a for example:
Do you think it's really a If it was, and this library will become a guide only for the one new to Python. = =! that is all . |
@kzinglzy Oh yes you're right haha, I see what happened. Wow, I need to be much more careful. Sorry about that and thanks for catching that! Also, I agree with pruning the trick list some of them did seem to be 'common' but of course that's difficult to answer. The goal I believe should be surprising/novel and useful. The list copy is one of the first things you learn in almost any python resource that talks about lists. It also should mention that it copies without aliasing, so that the copy is not another reference to the same list. If it's going to be that beginner friendly. @brennerm I still need to be removed from the contributor list, as I have not. |
@kzinglzy For sure there will be some examples that seem like normal usage to you, but contain additional value to others. list([1, 2, 3]) Considering that [1, 2, 3][:] is less obvious and twice as fast makes it a trick to me. Nevertheless I'm open for every feedback and appreciate your opinion. |
#!/usr/bin/env python
"""
# We could make dict object more readable using json module
# Source
dic = {u'favorited': False, u'truncated': False, u'created_at': u'Mon Sep 24 03:35:21 +0000 2012', u'coordinates': None,
u'entities': {u'user_mentions': [], u'hashtags': [{u'indices': [20, 34], u'text': u'freebandnames'}], u'urls': []},
u'id_str': u'250075927172759552'}
# Output
{
"coordinates": null,
"created_at": "Mon Sep 24 03:35:21 +0000 2012",
"entities": {
"hashtags": [
{
"indices": [
20,
34
],
"text": "freebandnames"
}
],
"urls": [],
"user_mentions": []
},
"favorited": false,
"id_str": "250075927172759552",
"truncated": false
}
"""
import json
dic = {
u'favorited': False, u'truncated': False, u'created_at': u'Mon Sep 24 03:35:21 +0000 2012', u'coordinates': None,
u'entities': {u'user_mentions': [], u'hashtags': [{u'indices': [20, 34], u'text': u'freebandnames'}], u'urls': []},
u'id_str': u'250075927172759552'
}
print(json.dumps(dic, sort_keys=True, indent=4))
# often for fast debug prints I use it like this:
# import json; print(json.dumps(dic_object, sort_keys=True, indent=4)) |
This one isn't good enough: #! /usr/bin/env python3
"""loop over dicts that share (some) keys"""
dctA = {'a': 1, 'b': 2, 'c': 3}
dctB = {'b': 4, 'c': 5, 'd': 6}
for ky in set(dctA) & set(dctB):
print(ky) Because in third python you could write simply:
|
@illuz, for which kind of tasks, we need this dangerous trick? #! /usr/bin/env python3
"""set global variables from dict"""
d = {'a': 1, 'b': 'var2', 'c': [1, 2, 3]}
globals().update(d)
print(a, b, c) |
@smiren |
@axiaoxin |
@brennerm, It is notation from shell(bash): echo view{keys,values,items} -> viewkeys viewvalues viewitems |
|
Hey @isayme, |
List some tricks, maybe help~
|
A less known feature is ` operator calls the obj.__ repr __. (or repr(obj) ) Not sure if it's worth adding. Edit: Github parses out ` |
@st0le |
@isayme |
As I understand, the backticks were removed in Py3. But here's the gist, http://stackoverflow.com/a/20521892 |
complex unpacking
even more complex unpacking
inspiration: https://twitter.com/renfredxh/status/586653125970386945 |
@brennerm I know, but the old example didn't have list literals on the left hand side and no nesting. |
@agumonkey [a],[b] = [[1],[2]] you could just do a, b = 1, 2 which is way more readable IMO. |
@brennerm yeah but unpacking is not only for hand made assignment, you may get [[1], [2]] as another function return value. |
No description provided.
The text was updated successfully, but these errors were encountered: