Some interesting and useful python skills.
a, b = 1, 2
print(a, b)
a, b = b, a
print(a, b)
a = ["python", "is", "awesome"]
print(" ".join(a))
a = [1, 2, 2, 3, 5, 7, 1, 1, 1]
print(max(set(a), key=a.count))
"""
Use Counter from collections
"""
from collections import Counter
cnt = Counter(a)
print(cnt.most_common(3))
# 3 代表取前3个
from collections import Counter
str1 = "sadassa"
str2 = "sadasas"
resbool = Counter(str1) == Counter(str2)
print(resbool)
a = "sadsadkslad"
a = [1, 2, 3, 4, 8]
print(a[::-1])
print(reversed(a))
#transpose 2d array [[a, b], [c, d], [e, f]] -> [[a, c, e], [b, d, f]]
original = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transpose = zip(*original)
print(list(transpose))
d = {'apple':10, 'orange': 20, 'banana': 5, 'tomatto': 1}
print(sorted(d.items(), key=lambda x: x[1]))
from operator import itemgetter
print(sorted(d.items(), key=itemgetter(1)))
print(sorted(d, key=d.get))
a = [1, 23, 34, 5, 4]
for el in a:
if el == 0:
break
else:
print('did not break the loop.')
items = ['foo', 'bar', 'xyz']
print(','.join(items))
numbers = [2, 3, 5, 10]
print(','.join(map(str, numbers)))
d1 = {'a':1}
d2 = {'b':2}
d1.update(d2)
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__)
items = [1, 2, 2, 2, 3]
newitem = list(set(items))
from collections import OrderedDict
items = ["foo", "bar", "bar", "foo"]
print(list(OrderedDict.fromkeys(items).keys()))
def getAllIndices(element, alist):
"""
Find the index of an element in a list. The element can appear multiple times.
input: alist - a list
element - objective element
output: index of the element in the list
"""
result = []
offset = -1
while True:
try:
offset = alist.index(element, offset + 1)
except ValueError:
return result
result.append(offset)