Python Code Snippets
2020-01-31
- 使用 RMarkdown 的
child
参数,进行文档拼接。 - 这样拼接以后的笔记方便复习。
- 相关问题提交到 Issue
参考 Grifski (2019)
1 build dict
{'id': 1, 'color': 'red', 'style': 'bold'}
{'id': 1, 'color': 'red', 'style': 'bold'}
启发下面。
2 flip keys and values when values is distinct
{1: 'id', 'red': 'color', 'bold': 'style'}
{1: 'id', 'red': 'color', 'bold': 'style'}
3 merge each value of two lists
[2, [7, 7], [2, 1], [8374163, 2314567], [84302738, 0]]
array([2, list([7, 7]), list([2, 1]), list([8374163, 2314567]),
list([84302738, 0])], dtype=object)
如果是 int 结构就直接相加,如果是 list 结构就合并。
7 sort dict
csv_mapping_list = [
{
"Name": "Jeremy",
"Age": 25,
"Favorite Color": "Blue"
},
{
"Name": "Ally",
"Age": 41,
"Favorite Color": "Magenta"
},
{
"Name": "Jasmine",
"Age": 29,
"Favorite Color": "Aqua"
}
]
[{'Name': 'Jeremy', 'Age': 25, 'Favorite Color': 'Blue'},
{'Name': 'Jasmine', 'Age': 29, 'Favorite Color': 'Aqua'},
{'Name': 'Ally', 'Age': 41, 'Favorite Color': 'Magenta'}]
8 merge two dict
{'Yusuke Urameshi': 'Spirit Gun', 'Hiei': 'Jagan Eye'}
{'Yusuke Urameshi': 'Spirit Gun', 'Hiei': 'Jagan Eye'}
9 print string like glue
My name is Jeremy, and I am 25 years old.
# String formatting using f-Strings (Python 3.6+)
print('My name is {name}, and I am {age} years old.')
My name is {name}, and I am {age} years old.
# String formatting using modulus operator
print('My name is %s, and I am %d years old.' % (name, age))
My name is Jeremy, and I am 25 years old.
# String formatting using format function with ordered parameters
print('My name is {}, and I am {} years old.'.format(name, age))
# String formatting using format function with named parameters
print('My name is {a}, and I am {b} years old.'.format(a=name, b=age))
My name is Jeremy, and I am 25 years old.
My name is Jeremy, and I am 25 years old.
附录
参考文献
Grifski, Jeremy. 2019. “71 Python Code Snippets for Everyday Problems.” The Renegade Coder. 2019. https://therenegadecoder.com/code/python-code-snippets-for-everyday-problems/.