a, b = 5, 10
print(a, b) # 5 10
a, b = b, a
print(a, b) # 10 5
将列表中的所有元素组合成字符串
a = ['Python', 'is', 'awesome']
print(' '.join(a)) # Python is awesome
a = [1, 2, 3, 1, 2, 3, 2, 2, 4, 5, 1]
print(max(set(a), key = a.count)) # 2
from collections import Counter
count = Counter(a)
print(count.most_common()) # [(2, 4), (1, 3), (3, 2), (4, 1), (5, 1)]
from collections import Counter
str1 = 'Hello Word'
str2 = 'Word Hello'
print(Counter(str1) == Counter(str2)) # True
a = 'abcdefghijklmnopqrstuvwxyz'
print(a[::-1]) # zyxwvutsrqponmlkjihgfedcba
a = [1, 2, 3, 4, 5]
print(a[::-1]) # [5, 4, 3, 2, 1]
matrix = [[1, 2, 3], [4, 5, 6]]
transposed = zip(*matrix)
print(list(transposed)) # [(1, 4), (2, 5), (3, 6)]
d1 = {'a':1}
d2 = {'b':2}
print({**d1, **d2}) # {'a': 1, 'b': 2}
print(dict(d1.items() | d2.items())) # {'a': 1, 'b': 2}
d1.update(d2)
print(d1) # {'a': 1, 'b': 2}
lst = [40, 10, 20, 30]
def minIndex(lst):
return min(range(len(lst)), key=lst.__getitem__)
def maxIndex(lst):
return max(range(len(lst)), key=lst.__getitem__)
print(minIndex(lst)) # 1
print(maxIndex(lst)) # 0
lang = {'python':'.py', 'java':'.java'}
lang = dict(zip(lang.values(), lang.keys()))
print(lang) # {'.py': 'python', '.java': 'java'}
isinstance 函数可用于判断实例的类型,其实它的第二个参数可以是多个数据类型组成的元组
isinstance(x, (int, str))
# 等价于
isinstance(x, int) or isinstance(x, float)
# 类似的函数还有字符串的 startswith 方法和 endswith 方法
s.startswith(('"""', "'''"))
# 等价于
s.startswith("'''") or s.startswith('"""')
(完)