python数组
nums = [[0 for _ in range(3)] for _ in range(5)]
nums = [[0] * 3 for _ in range(5)]
随机值选取
import random
random_float = random.random()
random_int = random.randint(1, 10)
random_uniform = random.uniform(1.5, 5.5)
random_choice = random.choice(['apple', 'banana', 'cherry'])
random_sample = random.sample(range(100), 5)
items = [1, 2, 3, 4, 5]
random.shuffle(items)
python字典
hashtable = {}
hashtable = dict()
hashtable['one'] = "1"
hashtable.get(key, default=None)
value = hashtable.pop(key)
python 队列
- 三种实现方式:Queue(较慢)、list(最慢)、deque(最快)
deque
import collections
q = collections.deque()
q.append(1)
q.appendleft(1)
if q
a = q.popleft()
a = q.pop()
len(q)
list
q.append()
del q[0]
len(q)
if not q
Queue
import queue
q = queue.Queue()
q.put()
q.get()
q.qsize()
q.empty()
python defaultdict
collections.defaultdict(list)
import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = collections.defaultdict(list)
for k, v in s:
d[k].append(v)
print(d.items())
print(d.keys())
print(d.values())
collections.defaultdict(set)
import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = collections.defaultdict(set)
for k, v in s:
d[k].add(v)
print(d.items())
collections.defaultdict(int)
import collections
string = 'nobugshahaha'
count = defaultdict(int)
for key in string:
count[key] += 1
print(count.items())
python字符串
s = ' Hello world '
print(s.strip())
print(s.split())
print(s[::-1])
str = "Hello, World!"
print(str[0])
print(str[-1])
print(str[0:5])
print(len(str))
words = ['Hello', 'World']
print(" ".join(words))
words = ['Hello', 'World']
word = 'dhdkhkd'
print(sorted(words))
print(sorted(word))
print(ord('A'))
print(chr(97))
c.isdigit()
for ch in str:
print(ch)
遍历方法
for i in range(len(nums) - 1, -1, -1):
print(nums[i])
for i, num in enumerate(nums):
print(i, num)
表示最大值
maxx = float('inf')
maxx = math.inf
minn = float('-inf')
minn = -math.inf
排序函数
nums = [2, 24, 8, 6, 35, 7, 22, 30]
nums.sort()
nums.sort(reverse=True)
new_nums = sorted(nums)
nums = [[5,4],[5,5],[6,7],[2,3]]
nums.sort(key=lambda x: (x[0], -x[1]))
nums = [(0, 0, 1), (-1, 1, 2), (1, 1, 3), (-2, 2, 4), (0, 2, 6), (0, 2, 5), (2, 2, 7)]
nums.sort()
print(nums)