Python中的tilde操作符

Python中的tilde操作符,python,operators,Python,Operators,Python中tilde操作符的用法是什么 我可以考虑的一件事是在字符串或列表的两侧做一些事情,例如检查字符串是否为回文: def is_palindromic(s): return all(s[i] == s[~i] for i in range(len(s) / 2)) 还有什么好的用法吗?~是python中基本上计算-x-1 所以一张桌子看起来像 i ~i 0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 因此,对于i=0,它将s[0]与s[l

Python中tilde操作符的用法是什么

我可以考虑的一件事是在字符串或列表的两侧做一些事情,例如检查字符串是否为回文:

def is_palindromic(s):
    return all(s[i] == s[~i] for i in range(len(s) / 2)) 
还有什么好的用法吗?

~
是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]
进行比较

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

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


在Python中,对于整数,整数的位是反向的(如
b中所示,
~
除了是一个按位补码运算符外,还可以帮助还原布尔值,尽管这不是传统的
bool
类型,而是您应该使用
numpy.bool


这在

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

有时,反转逻辑值可能很有用,例如,below
~
运算符用于清理数据集并返回不带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()]

这是一个次要的用法是平铺

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]
上面的代码来自“动手机器学习”

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

就像你用减号表示整数索引一样

ex)

这和我的一样吗


print(array[~1])

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

[0, 1, 2, 3, 4, 5, 6, 7, 8]
    ^                 ^
    i                ~i
我正在解决这个问题,我遇到了一个名为的用户

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

标准溶液为:

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

我唯一一次在实践中使用它是在
numpy/pandas
中。例如,使用
.isin()

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

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

请注意,由特殊方法
\uuuuu invert\uuuu
实现的一元补码运算符
~
not
运算符无关,后者在逻辑上对2.x中的
\uuuuu bool\uuuu
返回的值求反。它也与
-
一元求反运算符无关,由
\uuuu neg\uuuu
实现。例如,
~True==-2
,这不是
或假,
-False==0
,这仍然是假。@eryksun,虽然你说的是对的(
-False==0
),但它令人困惑,因为你说的是
~
,而
~False==1
这不是假。@Hermedelazari,第二个例子是比较算术否定(
\uuuu neg\uuuu
)。可能我应该继续使用
True
,例如
-True==-1
,它不是-2或
False
或False,这会更清楚地将它链接回
~True
结果,而且
bool
的算术求反与其逻辑求不同。我不想深陷其中。我只是强调了3个操作和有时会混淆的底层特殊方法。
numpy.NaN
似乎被定义为
numpy.float
。如果我尝试
~numpy.NaN
,python会抱怨,没有为类型
numpy.float
@M.Herzkamp定义一元运算符
~
,这是正确的。NaN、+Inf和-Inf是浮点数的特例。将浮点数的位反转将产生无意义的结果,因此Python不允许这样做。这就是为什么您需要首先对数据数组调用.isnull()或np.isnan(),然后反转生成的布尔值。请注意,
~True
会导致
-2
,而对于numpy布尔值
~np。True
会导致
False
。好提示!我在这里看到它用于对数据集进行排序:这主要是因为从
~I
中得出的值(即负值)充当数组索引的起点,python乐于接受数组索引,从而使索引环绕并从后面拾取。
>>> df.isin([0, 2])
        num_legs  num_wings
falcon      True       True
dog        False       True
>>> ~df.isin([0, 2])
        num_legs  num_wings
falcon     False       False
dog        True        False