Python Tips
Posted on Wednesday, Jul 01, 2020 in programming • Tagged with python, tips, lists, functools, itertools, timezone
A collection of small Python scripts and tips.
This post is based on a Twitter thread I started in April 2020 and works as a centralized way to read all the tips in an easier format than Twitter's 280 characters.
Both will be updated frequently.
List Flatten without explicit loops
- Using Itertools' chain
1 2 3 4 5 6 | import itertools
test = [[-1, -2], [30, 40], [25, 35]]
list(itertools.chain.from_iterable(test))
>> [-1, -2, 30, 40, 25, 35]
|
- Using map and strings (Suggested by @Romestantc )
1 2 3 4 | test = [[-1, -2], [30, 40], [25, 35]]
map(int, ''.join(c for c in test.__str__() if c not in '[]').split(',') )
>> [-1, -2, 30, 40, 25, 35]
|
Not pretty in my opinion ;)
Count individual items of any iterable
1 2 3 4 5 6 7 8 | from collections import Counter
count = Counter(['a', 'b', 'c', 'a', 'a', 'b', 'd'])
print(count)
>> Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})
count['a']
>> 3
|
Repeat a series of values from any iterable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import itertools as it
data = it.cycle([1, 2])
for i in range(10):
print(next(data))
>> 1
2
1
2
1
2
1
2
1
2
|
Name slices to reuse them
1 2 3 4 5 6 7 8 | # slice(start, end, step)
STEPTWO = slice(None, None, 2)
integer_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
integer_list[STEPTWO]
>> [0, 2, 4, 6, 8]
|
This is the same as:
1 | integer_list[::2]
|
Reverse any "indexable" collection that supports slices
1 2 3 4 5 6 | # slice(None, None, -1) or [::-1]
integer_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
integer_list[::-1]
>> [9, 8, 7, 6, 5 … |
Continue reading