a = [[1, 2, 3], [4, 5, 6]] print(list(map(list, zip(*a))))
a = dict(a=1, b=2, c=3) print(dict(zip(a.values(), a.keys())))
print(list(zip(*(iter([1, 2, 3, 4, 5, 6]),) * 3))) # [(1, 2, 3), (4, 5, 6)]
print(any([])) # False print(all([])) # True print(all([1,2,3,0])) # False
my_long_text = ("We are no longer the knights who say Ni! " "We are now the knights who say ekki-ekki-" "ekki-p'tang-zoom-boing-z'nourrwringmm!") print(my_long_text) # We are no longer the knights who say Ni! We are now the knights who say ekki-ekki-ekki-p'tang-zoom-boing-z'nourrwringmm!
def product(a, b): return a * b def subtract(a, b): return a - b b = True print((product if b else subtract)(1, 1))
d = {'apple': 10, 'orange': 20, 'banana': 5, 'rotten tomato': 1} print(sorted(d, key=d.get)) # ['rotten tomato', 'banana', 'apple', 'orange']
exec("print('Hello ' + s)", {'s': 'World!'}) # exec can be used to execute Python code during runtime variables can be handed over as a dict
[(c, *d, [*e]), f, *g] = [[1, 2, 3, 4, [5, 5, 5]], 6, 7, 8] print(c, d, e, f, g) # 1 [2, 3, 4] [5, 5, 5] 6 [7, 8]
import itertools a = [[1, 2], [3, 4], [[5,6],[7,8]]] print(list(itertools.chain(*a))) # [1, 2, 3, 4, [5, 6], [7, 8]]
把嵌套的也flatten?python
a = [[1, 2], [3, 4], [[5, 6], [7, 8]]] a = eval('[%s]' % repr(a).replace('[', '').replace(']', '')) print(a) # [1, 2, 3, 4, 5, 6, 7, 8]
更簡單?git
a = [[1, 'a', ['cat'], 2], [[[3], 'a', 'm', [1, 2, 3], [1, [1, 2, 3]]]], 'dog'] flatten = lambda L: eval(str(L).replace('[', '*[')[1:]) flatten(a)
dctA = {'a': 1, 'b': 2, 'c': 3} dctB = {'b': 4, 'c': 3, 'd': 6} # loop over dicts that share (some) keys in Python3 for ky in dctA.keys() & dctB.keys(): print(ky) # loop over dicts that share (some) keys and values in Python3 for item in dctA.items() & dctB.items(): print(item)
"""split a string max times""" string = "a_b_c" print(string.split("_", 1)) # ['a', 'b_c'] """use maxsplit with arbitrary whitespace""" s = "foo bar foobar foo" print(s.split(None, 2)) # ['foo', 'bar', 'foobar foo']
d1 = {'a': 1} d2 = {'b': 2} # python 3.5 print({**d1, **d2}) print(dict(d1.items() | d2.items())) d1.update(d2) print(d1)
lst = [40, 10, 20, 30] def minIndex(lst): return min(range(len(lst)), key=lst.__getitem__) # use xrange if < 2.7 def maxIndex(lst): return max(range(len(lst)), key=lst.__getitem__) # use xrange if < 2.7 print(minIndex(lst)) print(maxIndex(lst))
from collections import OrderedDict items = ["foo", "bar", "bar", "foo"] print(list(OrderedDict.fromkeys(items).keys()))
def foo(): d = {'a': 1, 'b': 'var2', 'c': [1, 2, 3]} globals().update(d) foo() print(a, b, c)
l = [4, 2, 3, 5, 1] print("original list: ", l) values, indices = zip(*sorted((a, b) for (b, a) in enumerate(l))) # now values contains the sorted list and indices contains # the indices of the corresponding value in the original list print("sorted list: ", values) print("original indices: ", indices) # note that this returns tuples, but if necessary they can # be converted to lists using list()
from collections import defaultdict tree = lambda: defaultdict(tree) users = tree() users['harold']['username'] = 'chopper' users['matt']['password'] = 'hunter2'
for i in range(5): for j in range(6): print(i * j) if i * j == 20: break else: continue break