欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

电报频道_我的电报频道@pythonetc的提示和技巧,2019年6月

程序员文章站 2022-05-17 08:13:24
...

电报频道

电报频道_我的电报频道@pythonetc的提示和技巧,2019年6月

It is a new selection of tips and tricks about Python and programming from my ********-channel @pythonetc.

这是我的********频道@pythonetc中有关Python和编程的一些新技巧和窍门。

Previous publications

以前的出版物

电报频道_我的电报频道@pythonetc的提示和技巧,2019年6月

The \ symbol in regular string have special meaning. \t is tab character, \r is carriage return and so on.

常规字符串中的\符号具有特殊含义。 \t是制表符, \r是回车,依此类推。

You can use raw-strings to disable this behaviour. r'\t' is just backslash and t.

您可以使用原始字符串来禁用此行为。 r'\t'只是反斜杠和t

You obviously can’t use ' inside r'...'. However, it still can be escaped by \, but \ is preserved in the string:

您显然不能使用' inside r'...' 。 但是,它仍然可以通过\进行转义,但是\保留在字符串中:

>>> print(r'It\'s insane!')
It\'s insane!
电报频道_我的电报频道@pythonetc的提示和技巧,2019年6月

List comprehensions may contain more than one for and if clauses:

列表推导可能包含多个forif子句:

In : [(x, y) for x in range(3) for y in range(3)]
Out: [
    (0, 0), (0, 1), (0, 2),
    (1, 0), (1, 1), (1, 2),
    (2, 0), (2, 1), (2, 2)
]
In : [
    (x, y)
    for x in range(3)
    for y in range(3)
    if x != 0
    if y != 0
]
Out: [(1, 1), (1, 2), (2, 1), (2, 2)]

Also, any expression within for and if may use all the variables that are defined before:

同样, forif任何表达式都可以使用之前定义的所有变量:

In : [
    (x, y)
    for x in range(3)
    for y in range(x + 2)
    if x != y
]
Out: [
    (0, 1),
    (1, 0), (1, 2),
    (2, 0), (2, 1), (2, 3)
]

You can mix ifs and fors however you want:

您可以根据需要将s和for混合if

In : [
    (x, y)
    for x in range(5)
    if x % 2
    for y in range(x + 2)
    if x != y
]
Out: [
    (1, 0), (1, 2),
    (3, 0), (3, 1), (3, 2), (3, 4)
]
电报频道_我的电报频道@pythonetc的提示和技巧,2019年6月

The sorted function allows you to provide custom method for sorting. It’s done with the key argument, which describes how to convert original values to values that are actually compared:

sorted功能允许您提供自定义方法进行排序。 这是通过key参数完成的,该参数描述了如何将原始值转换为实际比较的值:

>>> x = [dict(name='Vadim', age=29), dict(name='Alex', age=4)]
>>> sorted(x, key=lambda v: v['age'])
[{'age': 4, 'name': 'Alex'}, {'age': 29, 'name': 'Vadim'}]

Alas, not all libraries that work with comparison support something like this key argument. Notable examples are heapq (partial support) and bisect (no support).

las,并非所有可用于比较的库都支持类似此key参数的内容。 值得注意的例子是heapq (部分支持)和bisect (不支持)。

There are two ways to deal with the situation. The first is to use custom objects that do support proper comparsion:

有两种方法可以处理这种情况。 第一种是使用支持正确比较的自定义对象:

>>> class User:
...     def __init__(self, name, age):
...         self.name = name
...         self.age = age
...     def __lt__(self, other):
...         return self.age < other.age
...
>>> x = [User('Vadim', 29), User('Alex', 4)]
>>> [x.name for x in sorted(x)]
['Alex', 'Vadim']

However, you may have to create several versions of such classes since there are more than one way to compare objects. It can be tiresome, but can be easily solved by the second way.

但是,由于有不止一种比较对象的方法,因此您可能必须创建此类的多个版本。 这可能很累,但可以通过第二种方法轻松解决。

Instead of creating custom objects you may use tuples (a, b) where a is the value to compare (a.k.a. prioirty) and b is the original value:

代替创建自定义对象,您可以使用元组(a, b) ,其中a是要比较的值(又名prioirty),而b是原始值:

>>> users = [dict(name='Vadim', age=29), dict(name='Alex', age=4)]
>>> to_sort = [(u['age'], u) for u in users]
>>> [x[1]['name'] for x in sorted(to_sort)]
['Alex', 'Vadim']
电报频道_我的电报频道@pythonetc的提示和技巧,2019年6月

The difference between function definition and generator definition is the presence of the yield keyword in the function body:

函数定义和生成器定义之间的区别在于,函数主体中存在yield关键字:

In : def f():
...:     pass
...:

In : def g():
...:     yield
...:

In : type(f())
Out: NoneType

In : type(g())
Out: generator

That means that in order to create an empty generator you have to do something like this:

这意味着要创建一个空的生成器,您必须执行以下操作:

In : def g():
...:     if False:
...:         yield
...:

In : list(g())
Out: []

However, since yield from supports simple iterators that better looking version would be this:

但是,由于yield from支持简单的迭代器,因此外观更好的版本是这样的:

def g():
    yield from []
电报频道_我的电报频道@pythonetc的提示和技巧,2019年6月

In Python, you can chain comparison operators:

在Python中,您可以链接比较运算符:

>>> 0 < 1 < 2
True
>>> 0 < 1 < 0
False

Such chains don’t have to be mathematically valid, you can mix > and <:

这样的链不必在数学上有效,您可以将><混合使用:

>>> 0 < 1 > 2
False
>>> 0 < 1 < 2 > 1 > 0
True

Other operators such as ==, is and in are also supported:

还支持其他运算符,例如==isin

>>> [] is not 3 in [1, 2, 3]
True

Every operator is applied to the two nearest operands. a OP1 b OP2 c is strictly equal to (a OP1 b) AND (b OP2 c). No comparison between a and c is implied:

每个运算符都应用于两个最接近的操作数。 a OP1 b OP2 c严格等于(a OP1 b) AND (b OP2 c) 。 没有暗示ac之间a比较:

class Spy:
    def __init__(self, x):
        self.x = x

    def __eq__(self, other):
        print(f'{self.x} == {other.x}')
        return self.x == other.x

    def __ne__(self, other):
        print(f'{self.x} != {other.x}')
        return self.x != other.x

    def __lt__(self, other):
        print(f'{self.x} < {other.x}')
        return self.x < other.x

    def __le__(self, other):
        print(f'{self.x} <= {other.x}')
        return self.x <= other.x

    def __gt__(self, other):
        print(f'{self.x} > {other.x}')
        return self.x > other.x

    def __ge__(self, other):
        print(f'{self.x} >= {other.x}')
        return self.x >= other.x


s1 = Spy(1)
s2 = Spy(2)
s3 = Spy(3)

print(s1 is s1 < s2 <= s3 == s3)

Output:

输出:

1 < 2
2 <= 3
3 == 3
True

翻译自: https://habr.com/en/company/mailru/blog/458688/

电报频道