Python 黑魔法(持续收录)

Python 黑魔法(持续收录)

zip 对矩阵进行转置

a = [[1, 2, 3], [4, 5, 6]]

print(list(map(list, zip(*a))))

zip 反转字典

a = dict(a=1, b=2, c=3)
print(dict(zip(a.values(), a.keys())))

将list分成n份

print(list(zip(*(iter([1, 2, 3, 4, 5, 6]),) * 3)))
# [(1, 2, 3), (4, 5, 6)]

all & any 函数

  • all:如果iterable的所有元素不为0、''、False或者iterable为空,all(iterable)返回True,否则返回False
  • any: 如果所有元素中有一个值不是0、''或False,那么结果就为True,否则为False
print(any([]))
# False
print(all([]))
# True
print(all([1,2,3,0]))
# False

Concatenate long strings elegantly across line breaks in code

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!

calling different functions with same arguments based on condition

def product(a, b):
    return a * b


def subtract(a, b):
    return a - b


b = True
print((product if b else subtract)(1, 1))

Sort dict keys by value

d = {'apple': 10, 'orange': 20, 'banana': 5, 'rotten tomato': 1}

print(sorted(d, key=d.get))

# ['rotten tomato', 'banana', 'apple', 'orange']

exec

exec("print('Hello ' + s)", {'s': 'World!'})
# exec can be used to execute Python code during runtime variables can be handed over as a dict

unpacking

[(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]

flatten list

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?

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]

更简单?

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)

dict求交

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

"""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)

Find Index of Min/Max Element

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))

remove duplicate items from list and keep order

from collections import OrderedDict

items = ["foo", "bar", "bar", "foo"]

print(list(OrderedDict.fromkeys(items).keys()))

set global variables from dict

def foo():
    d = {'a': 1, 'b': 'var2', 'c': [1, 2, 3]}
    globals().update(d)


foo()
print(a, b, c)

Sort a list and store previous indices of values

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()

None

from collections import defaultdict

tree = lambda: defaultdict(tree)


users = tree()
users['harold']['username'] = 'chopper'
users['matt']['password'] = 'hunter2'

for_else 跳出多层循环

for i in range(5):
    for j in range(6):
        print(i * j)
        if i * j == 20:
            break
    else:
        continue
    break

参考资料

  1. Pytricks
  2. hidden features in Python
posted @ 2017-03-31 17:26  狂徒归来  阅读(946)  评论(1编辑  收藏  举报