问题:Python中的代字号运算符

Python中的tilde运算符有什么用?

我能想到的一件事是在字符串或列表的两面都做一些事情,例如检查字符串是否为回文:

def is_palindromic(s):
    return all(s[i] == s[~i] for i in range(len(s) / 2)) 

还有其他好的用法吗?

What’s the usage of the tilde operator in Python?

One thing I can think about is do something in both sides of a string or list, such as check if a string is palindromic or not:

def is_palindromic(s):
    return all(s[i] == s[~i] for i in range(len(s) / 2)) 

Any other good usage?


回答 0

它是从C借来的一元运算符(采用单个参数),其中所有数据类型只是解释字节的不同方式。这是“取反”或“补码”操作,其中输入数据的所有位都取反。

在Python中,对于整数,该整数的二进制补码表示形式的位被颠倒(b <- b XOR 1对于每个单独的位而言),并且结果再次解释为二进制补码整数。因此对于整数,~x等于(-x) - 1

~运算符的形式化形式为operator.invert。要在您自己的类中支持此运算符,请为其提供一个__invert__(self)方法。

>>> import operator
>>> class Foo:
...   def __invert__(self):
...     print 'invert'
...
>>> x = Foo()
>>> operator.invert(x)
invert
>>> ~x
invert

对于具有相同类实例的实例的“补码”或“逆”有意义的任何类,都可以用作反转运算符。但是,如果误用了运算符,则可能导致混乱,因此请确保在为__invert__类提供方法之前这样做确实有意义。(请注意,字节字符串[ex:'\xff']不支持此运算符,即使将字节字符串的所有位取反也很有意义。)

It is a unary operator (taking a single argument) that is borrowed from C, where all data types are just different ways of interpreting bytes. It is the “invert” or “complement” operation, in which all the bits of the input data are reversed.

In Python, for integers, the bits of the twos-complement representation of the integer are reversed (as in b <- b XOR 1 for each individual bit), and the result interpreted again as a twos-complement integer. So for integers, ~x is equivalent to (-x) - 1.

The reified form of the ~ operator is provided as operator.invert. To support this operator in your own class, give it an __invert__(self) method.

>>> import operator
>>> class Foo:
...   def __invert__(self):
...     print 'invert'
...
>>> x = Foo()
>>> operator.invert(x)
invert
>>> ~x
invert

Any class in which it is meaningful to have a “complement” or “inverse” of an instance that is also an instance of the same class is a possible candidate for the invert operator. However, operator overloading can lead to confusion if misused, so be sure that it really makes sense to do so before supplying an __invert__ method to your class. (Note that byte-strings [ex: '\xff'] do not support this operator, even though it is meaningful to invert all the bits of a byte-string.)


回答 1

~是python中按位补码运算符,它本质上计算-x - 1

所以一张桌子看起来像

i  ~i  
0  -1
1  -2
2  -3
3  -4 
4  -5 
5  -6

因此,对于i = 0它会比较s[0]s[len(s) - 1],对i = 1s[1]s[len(s) - 2]

至于您的其他问题,这对于一系列按位破解可能很有

~ is the bitwise complement operator in python which essentially calculates -x - 1

So a table would look like

i  ~i  
0  -1
1  -2
2  -3
3  -4 
4  -5 
5  -6

So for i = 0 it would compare s[0] with s[len(s) - 1], for i = 1, s[1] with s[len(s) - 2].

As for your other question, this can be useful for a range of bitwise hacks.


回答 2

除了是按位补码运算符外,~还可以帮助还原布尔值,尽管bool此处不是常规类型,而是应使用numpy.bool_


对此进行了解释,

import numpy as np
assert ~np.True_ == np.False_

有时,反转逻辑值可能很有用,例如,下面的~运算符用于清除数据集并返回不带NaN的列。

from numpy import NaN
import pandas as pd

matrix = pd.DataFrame([1,2,3,4,NaN], columns=['Number'], dtype='float64')
# Remove NaN in column 'Number'
matrix['Number'][~matrix['Number'].isnull()]

Besides being a bitwise complement operator, ~ can also help revert a boolean value, though it is not the conventional bool type here, rather you should use numpy.bool_.


This is explained in,

import numpy as np
assert ~np.True_ == np.False_

Reversing logical value can be useful sometimes, e.g., below ~ operator is used to cleanse your dataset and return you a column without NaN.

from numpy import NaN
import pandas as pd

matrix = pd.DataFrame([1,2,3,4,NaN], columns=['Number'], dtype='float64')
# Remove NaN in column 'Number'
matrix['Number'][~matrix['Number'].isnull()]

回答 3

应该注意的是,在数组索引的情况下,array[~i]等于reversed_array[i]。可以将其视为从数组末尾开始的索引:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
    ^                 ^
    i                ~i

One should note that in the case of array indexing, array[~i] amounts to reversed_array[i]. It can be seen as indexing starting from the end of the array:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
    ^                 ^
    i                ~i

回答 4

我在实践中唯一使用过此功能的时间是使用numpy/pandas。例如,使用.isin() dataframe方法

他们在文档中显示了这个基本示例

>>> df.isin([0, 2])
        num_legs  num_wings
falcon      True       True
dog        False       True

但是,如果您不希望所有行都不在 [0,2]中怎么办?

>>> ~df.isin([0, 2])
        num_legs  num_wings
falcon     False       False
dog        True        False

The only time I’ve ever used this in practice is with numpy/pandas. For example, with the .isin() dataframe method.

In the docs they show this basic example

>>> df.isin([0, 2])
        num_legs  num_wings
falcon      True       True
dog        False       True

But what if instead you wanted all the rows not in [0, 2]?

>>> ~df.isin([0, 2])
        num_legs  num_wings
falcon     False       False
dog        True        False

回答 5

我正在解决这个leetcode问题,遇到了一个叫Zitao Wang的用户,这个漂亮的解决方案

问题是这样的:对于给定数组中的每个元素,在不使用除法和O(n)时间的情况下找到所有剩余数字的乘积

标准解决方案是:

Pass 1: For all elements compute product of all the elements to the left of it
Pass 2: For all elements compute product of all the elements to the right of it
        and then multiplying them for the final answer 

他的解决方案只利用了一个for循环。他使用实时计算左乘积和右乘积~

def productExceptSelf(self, nums):
    res = [1]*len(nums)
    lprod = 1
    rprod = 1
    for i in range(len(nums)):
        res[i] *= lprod
        lprod *= nums[i]
        res[~i] *= rprod
        rprod *= nums[~i]
    return res

I was solving this leetcode problem and I came across this beautiful solution by a user named Zitao Wang.

The problem goes like this for each element in the given array find the product of all the remaining numbers without making use of divison and in O(n) time

The standard solution is:

Pass 1: For all elements compute product of all the elements to the left of it
Pass 2: For all elements compute product of all the elements to the right of it
        and then multiplying them for the final answer 

His solution uses only one for loop by making use of. He computes the left product and right product on the fly using ~

def productExceptSelf(self, nums):
    res = [1]*len(nums)
    lprod = 1
    rprod = 1
    for i in range(len(nums)):
        res[i] *= lprod
        lprod *= nums[i]
        res[~i] *= rprod
        rprod *= nums[~i]
    return res

回答 6

这是次要用法,是波浪线…

def split_train_test_by_id(data, test_ratio, id_column):
    ids = data[id_column]
    in_test_set = ids.apply(lambda id_: test_set_check(id_, test_ratio)) 
    return data.loc[~in_test_set], data.loc[in_test_set]

上面的代码来自“动手学习机器”

您使用代字号(〜符号)替代-符号索引标记

就像您使用减号一样-用于整数索引

例如)

array = [1,2,3,4,5,6]
print(array[-1])

与…相同

print(array[~1])

This is minor usage is tilde…

def split_train_test_by_id(data, test_ratio, id_column):
    ids = data[id_column]
    in_test_set = ids.apply(lambda id_: test_set_check(id_, test_ratio)) 
    return data.loc[~in_test_set], data.loc[in_test_set]

the code above is from “Hands On Machine Learning”

you use tilde (~ sign) as alternative to – sign index marker

just like you use minus – is for integer index

ex)

array = [1,2,3,4,5,6]
print(array[-1])

is the samething as

print(array[~1])


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。