6

Python 的魅力(技巧几则)[编程的日常]

 3 years ago
source link: https://zhuanlan.zhihu.com/p/80261870
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python 的魅力(技巧几则)[编程的日常]

☑编程 ☑读书 ☑翻译 ☑太极

Python 让我喜欢的一大原因就是解决问题的小手段很多,犹如云中散手,出乎你的意料,让你看了之后恍然大悟:居然如此巧妙,只有想不到,没有做不到。

接下来介绍几个小手段,喜欢就点赞,赞越多今后分享也就越多。๑乛◡乛๑


  • 快速比较列表元素是否相同
from collections import Counter
a = [1, 2, 3]
b = [2, 3, 1]
c = [1, 2]
In [29]: Counter(a) == Counter(b)
Out[29]: True

In [30]: Counter(a) == Counter(c)
Out[30]: False

  • 一种字符串拼接的妙用
In [35]: s =("It is just a very very "
    ...: "long long long long long string.")

In [36]: s
Out[36]: 'It is just a very very long long long long long string.'

In [37]: l = ["abc", "efg" "hij", "klmm"]

In [38]: l
Out[38]: ['abc', 'efghij', 'klmm']

列表里的那个操作尤其骚气了。


  • 有关列表的 print() 操作
In [42]: l = ["abc", "efg", "hij"]

In [43]: print(*l)
abc efg hij

In [44]: print(*l, sep=", ")
abc, efg, hij

In [45]: print(*l, sep=", ", end=".\n")
abc, efg, hij.

  • 自定义“操作符”

大家知道 Python 无法自定义操作符,但是 Python 的小手段 Trick 是层出不穷的。

from functools import partial


class Infix(object):
    def __init__(self, func):
        self.func = func
    def __or__(self, other):
        return self.func(other)
    def __ror__(self, other):
        return Infix(partial(self.func, other))
    def __call__(self, v1, v2):
        return self.func(v1, v2)

然后试试看:

In [48]: @Infix
    ...: def multiply(x, y):
    ...:     return x * y
    ...:

In [49]: 10 |multiply| 9000
Out[49]: 90000

In [50]: curry = Infix(partial)

In [51]: def f(x, y, z):
    ...:     return x + y + z
    ...:

In [52]: g = f |curry| 10 |curry| 20 |curry| 30

In [53]: g()
Out[53]: 60

  • 提取字符串里的容器结构
In [54]: import ast

In [55]: a = "[10, 50, 90]"

In [56]: ast.literal_eval(a)
Out[56]: [10, 50, 90]

In [57]: b = "[10, 50, 90], (60, 130)"

In [58]: ast.literal_eval(b)
Out[58]: ([10, 50, 90], (60, 130))

In [59]: ast.literal_eval(b)[1][1]
Out[59]: 130

好了,我不知道哪种编程语言的 Hack 小手段有 Python 这么多。Python 的开发效率确实高,但不代表 Python 简单。要用好 Python,小手段是很重要的。(^_^)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK