workers = [1, 2, 3, 4]
# Using *workers in a print statement
print(*workers) # Output: 1 2 3 4
default: Functions: max() and min() support the default parameter.
min/max([], default=0) # Returns 0
遍历dictionary:
```python
for k,v in d.items():
v.reserse() #v is a list
```
number char coversion
char.isdigit()
char.isalpha()
Convert a Character to its ASCII/Unicode Number
char = 'A' number = ord(char) print(number) # Output: 65
Convert a Numeric Character to its Integer Value
char = '7' number = int(char) print(number) # Output: 7
Counter
Counter(list) returnr dict.
most_common(k) returns a list of (element, count) tuples sorted by counts.
return [i for i,_ in collections.Counter(nums).most_common(k)]
Sort
Define a lambda function to sort various data structures like lists, dictionaries, and tuples.
In-place vs. Copy:
sorted() returns a new sorted list.
.sort() sorts the list in place and returns None.
Sorting a List
# Example list of tuples
data = [(1, 3), (4, 1), (5, 2)]
# Sorting the list based on the second element of each tuple
sorted_data = sorted(data, key=lambda x: x[1])
# Output: [(4, 1), (5, 2), (1, 3)]
print(sorted_data)
Sorting a Dictionary by Value
# Example dictionary
data = {'a': 3, 'b': 1, 'c': 2}
# Sorting the dictionary by its values
sorted_data = sorted(data.items(), key=lambda x: x[1])
# Output: [('b', 1), ('c', 2), ('a', 3)]
print(sorted_data)
Sorting a List of Dictionaries
# Example list of dictionaries
data = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 22}, {'name': 'Doe', 'age': 30}]
# Sorting by the 'age' key
sorted_data = sorted(data, key=lambda x: x['age'])
# Output: [{'name': 'Jane', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Doe', 'age': 30}]
print(sorted_data)
deque
整个list 加入deque, extend()
d.extend(lst)
use cache in DP
from functools import lru_cache # Import lru_cache
@lru_cache(None)
filter
参数是一个函数和iterator,函数作用在每个iterator上
#滤掉所有非(),因为count返回返回1或0
s = "a(b)c)d"
result = ''.join(filter('()'.count, s))
print(result) # Output: "()()"