波浪符在Python中有什么用途?
我能想到的一件事是在字符串或列表的两侧做一些事情,比如检查字符串是否为回文:
def is_palindromic(s):
return all(s[i] == s[~i] for i in range(len(s) / 2))
还有其他好的用法吗?
波浪符在Python中有什么用途?
我能想到的一件事是在字符串或列表的两侧做一些事情,比如检查字符串是否为回文:
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]。
至于你的另一个问题,这可能对一系列位黑客有用。
其他回答
应该注意,在数组索引的情况下,array[~i]等于reversed_array[i]。它可以被视为从数组末尾开始的索引:
[0, 1, 2, 3, 4, 5, 6, 7, 8]
^ ^
i ~i
这是次要的用法是波浪…
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))
我在解决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
它叫做二进制一号的补体(~)
它返回一个数的二进制数的补数。它翻转比特。2的二进制是00000010。它的补数是11111101。
这是-3的二进制。结果是-3。类似地,~1的结果是-2。
~-3
输出:2
同样,-3的补是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()]