Python
Python snippets
- Read file with Chinese
import codecs
with codecs.open('areachn.json', 'r', 'utf-8') as fp:
a = json.load(fp)
- Filter list
test = range(-5, 5)
lessthanzero = list(filter(lambda x:x < 0, test))
- Sort list of turple
sorted(result, key=lambda x: x[0], reverse=True)
- Combine to list
a = [1, 2]
b = [3, 4]
c = a + b
- Sort a dictionary
import operator
x = {1:2, 3:4, 4:3, 1:0}
sorted_x = operator(x.items(), key=operator.itemgetter(1))
Filter dict by value
sorted_dict = {k: v for k, v in areadata.items() if v > 0}
- Reduce
from functools import reduce
product = reduce((lambda x, y: x+y), [1, 2, 3, 4])
- Date time format code
| Directive | Description | Example |
|---|---|---|
| %a | Weekday, short version | Wed |
| %A | Weekday, full version | Wednesday |
| %w | Weekday as number, 0-6, 0 is Sunday | 3 |
| %d | Day of month 01-31 | 31 |
| %b | Month name, short version | Dec |
| %B | Month name, full version | December |
| %y | Year, short version without century | 22 |
| %Y | Year, full version | 2022 |
| %H | Hour 00-23 | 17 |
| %I | Hour 00-12 | 05 |
| %p | AM/PM | PM |
| %M | Minute, 00-59 | 41 |
| %S | Second, 00-59 | 08 |
| %f | Microseconds, 000000-999999 | 548513 |
| %z | UTC offset | +0100 |
| %Z | Timezone | CST |
| %j | Day number of year 000-366 | 365 |
| %U | Week number of year, Sunday as first day of week | 52 |
| %W | Week number of year, Monday as first day of week | 52 |
| %c | Local version of date and time | Mon Dec 31 17:41:00 2022 |
| %x | Local version of date | 12/31/22 |
| %X | Local version of time | 17:41:00 |
| %% | A % character | % |