波浪符在Python中有什么用途?

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

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

还有其他好的用法吗?


当前回答

我唯一一次在实践中使用它是在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

其他回答

~是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 = 1时,s[1]和s[len(s) - 2]。

至于你的另一个问题,这可能对一系列位黑客有用。

这是次要的用法是波浪…

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]

上面的代码来自“Hands On Machine Learning”

您可以使用波浪号(~符号)作为-符号索引标记的替代

就像你用- - is表示整数索引一样

ex)

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

是一样的吗

打印(数组(~ 1))

它叫做二进制一号的补体(~)

它返回一个数的二进制数的补数。它翻转比特。2的二进制是00000010。它的补数是11111101。

这是-3的二进制。结果是-3。类似地,~1的结果是-2。

~-3

输出:2

同样,-3的补是2。

它是从C语言中借来的一元操作符(只接受一个参数),在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']不支持此运算符,尽管将字节串的所有位颠倒是有意义的。)

我在解决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