跳到主要内容

My Python Cheatsheet

Print

# concatenate with +
>>> import os
>>> print('Hello, ' + os.getlogin() + '! How are you?')
Hello, daniel.guo! How are you?

>>> import os
>>> print(f"Hello, {os.getlogin()}! How are you?")
Hello, daniel.guo! How are you?

Variables

# dynamic typed
>>> m = 0
>>> n = "abc"

# multiple assignments
>>> m, n, z = 0, "abc", False
>>> x = None

# Increment
>>> n = 10
>>> n = n + 1
>>> n += 1

If-else

# parentheses or curly braces are not required
x = 10
if x % 2 == 0:
n += 1
elif x % 5 == 0:
n += 2
else:
n += 3

Loops

x = 10
while (x < 100):
x += 10

# i from 0 to 4
for i in range(5):
print(i)

# i from 2 to 4
for i in range(2, 5):
print(i)

# i from 5 to 2
for i in range(5, 1, -1)
print(i)

Arrays

From Python 3.9+, list/set/dict can also have types, so no need to use List/Set/Dict from typing.

# array or list
data = [1, 2, 3]
data = list([2, 3, 4])

data.append(4)
data.pop()
data.insert(1, 7)

>>> print(data)
[2, 7, 3, 4]

data[0] = 11
data[2] = 13

>>> print(data)
[11, 7, 13, 4]

# initialize an array of size 5 and default value 0
>>> data = [0] * 5
>>> print(data)
[0, 0, 0, 0, 0]

len(data)

# last value of the array
data[-1]

# sub array
data[0:3]

# unpacking
a, b, c = [1, 2, 3]

# loop through an array
nums = [1, 3, 5, 7, 8]
for i in range(len(nums)):
print(nums(i))

for n in nums:
print(n)

# index with value
for i,n in enumerate(nums):
print(i, n)

# loop through multiple arrays simultaneously
nums1 = [1, 2, 3]
nums2 = [4, 5, 6]
for n1, n2 in zip(nums1, nums2):
print(n1, n2)

# reverse, sort: both in place, not return new data
nums = [1, 2, 3]
nums.reverse()
nums.sort()
nums.sort(reverse=True)
nums.sort(key=lambda x: len(x))

# list comprehension
>>> data = [i for i in range(5)]
>>> print(data)
[0, 1, 2, 3, 4]

Strings

>>> s = "hello world"
>>> s[0:2]
'he'
>>> s += "!"
>>> s
'hello world!'

# cannot assign to each item
>>> s[0] = 'H'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

# len to get the length of the string
>>> len(s)
12

# startswith
>>> s.startswith("hel")
True

# conversion with int
>>> int("100")
100
>>> str(200)
'200'

# ASCII value of a char
# useful when
>>> ord('a')
97
>>> ord('b') - ord('a')
1

# join a list of strings
>>> s_arr = ["hello", "world"]
>>> s = "-".join(s_arr)
>>> s
'hello-world'

# check if a string is alphanum
>>> s = "Abc123"
>>> s.isalnum()
True
>>> s = "abc 123 !"
>>> s.isalnum()
False

# to remove the newline character from a string
>>> "\na string \n".rstrip()
'\na string'
>>> "\na string \n".strip()
'a string'
>>> "\na string \n".lstrip()
'a string \n'

Set

# add and remove
my_set = set()
my_set.add(1)
my_set.add(2)
len(my_set)
my_set.remove(1)

if 1 in my_set:
print(my_set)

# list to set
>>> set([1, 2, 3])
{1, 2, 3}

# set comprehension
>>> my_set = { i for i in range(5) }
>>> my_set
{0, 1, 2, 3, 4}

Map/Hash

>>> my_dict = {}
>>> my_dict["LA"] = 100
>>> my_dict["GS"] = 90

>>> "LA" in my_dict
True
>>> len(my_dict)
2

>>> my_dict.pop("GS")
90

# get all values in a list
>>> list(my_dict.values())
[100]

# dict comprehension
>>> nums = [1, 3, 4]
>>> my_dict = { nums[i]: i for i in range(len(nums)) }
>>> my_dict
{1: 0, 3: 1, 4: 2}

# loop through maps
my_dict = { "Hello": 10, "world": 30 }
for key in my_dict:
print(key, my_dict[key])

for value in my_dict.values():
print(value)

for key, value in my_dict.items():
print(key, value)

# get value with default value
my_dict.get("hey", 50)

Tuples

tuples are like arrays/lists, but immutable

>>> tup = (1, 2, 3, 4)
>>> tup[0]
>>> tup[0:2]
(1, 2)
>>> tup[-1]
4

# cannot change
>>> tup[0] = 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

# tuple can be used as key for hash map/set
>>> my_map = { (1, 2): 3 }
>>> my_map[(1, 2)]
3

>>> my_set = set()
>>> my_set.add((1, 2))
>>> (1, 2) in my_set
True