我在整个项目中使用 Python 类型模块,我想知道是否有一种方法可以指定给定对象必须同时具有两种不同的类型。当您指定了两个协议,并期望单个对象满足这两个协议时,这种情况最明显地出现:
class ReturnsNumbers(Protocol):
def get_number(self) -> Int:
pass
class ReturnsLetters(Protocol):
def get_letter(self) -> str:
pass
def get_number_and_letter(x: <what should this be?>) -> None:
print(x.get_number(), x.get_letter())
Run Code Online (Sandbox Code Playgroud)
提前致谢!
I have quite a simple scenario where I'd like to test whether both elements of a two-dimensional array are (separately) members of a larger array - for example:
full_array = np.array(['A','B','C','D','E','F'])
sub_arrays = np.array([['A','C','F'],
['B','C','E']])
np.isin(full_array, sub_arrays)
Run Code Online (Sandbox Code Playgroud)
This gives me a single dimension output:
array([ True, True, True, False, True, True])
Run Code Online (Sandbox Code Playgroud)
showing whether elements of full_array are present in either of the two sub-arrays. I'd like instead a two-dimensional array showing the same thing for each of the two elements …
抱歉,这很简单,但是我在numpy文档中看不到任何内容。我有一个datetime64,我想知道是星期几。
与python不同datetime,datetime64它似乎没有.weekday()功能。但是它确实具有busday_offset()功能,这意味着它必须在幕后才能知道给定日期是星期几。任何帮助,不胜感激。
我有一个4x3布尔numpy数组,我试图返回一个大小相同的数组,除了原始每一行上第一个True值的位置外,它都是False.所以如果我有一个起始数组
all_bools = np.array([[False, True, True],[True, True, True],[False, False, True],[False,False,False]])
all_bools
array([[False, True, True], # First true value = index 1
[ True, True, True], # First true value = index 0
[False, False, True], # First true value = index 2
[False, False, False]]) # No True Values
Run Code Online (Sandbox Code Playgroud)
然后我想回来
[[False, True, False],
[True, False, False],
[False, False, True],
[False, False, False]]
Run Code Online (Sandbox Code Playgroud)
所以前三行的索引1,0和2已经设置为True而没有别的.基本上,原始方式中的任何True值(超出每行的第一个值)都设置为False.
我一直在用np.where和np.argmax来摆弄这个问题,我还没有找到一个好的解决方案 - 任何帮助都会感激不尽.这需要运行很多次,所以我想避免迭代.
我正在尝试使用新的 python 数据类来创建一些混合类(在我写这篇文章时,我认为这听起来像是一个轻率的想法),但我遇到了一些问题。看下面的例子:
从数据类导入数据类
@dataclass
class NamedObj:
name: str
def __post_init__(self):
print("NamedObj __post_init__")
self.name = "Name: " + self.name
@dataclass
class NumberedObj:
number: int = 0
def __post_init__(self):
print("NumberedObj __post_init__")
self.number += 1
@dataclass
class NamedAndNumbered(NumberedObj, NamedObj):
def __post_init__(self):
super().__post_init__()
print("NamedAndNumbered __post_init__")
Run Code Online (Sandbox Code Playgroud)
如果我再尝试:
nandn = NamedAndNumbered('n_and_n')
print(nandn.name)
print(nandn.number)
Run Code Online (Sandbox Code Playgroud)
我得到
NumberedObj __post_init__
NamedAndNumbered __post_init__
n_and_n
1
Run Code Online (Sandbox Code Playgroud)
暗示它已经运行__post_init__了NamedObj,但没有运行NumberedObj。我想要的是让 NamedAndNumbered__post_init__为它的两个混合类 Named 和 Numbered 运行。有人可能认为如果NamedAndNumbered有这样的就可以做到__post_init__:
def __post_init__(self):
super(NamedObj, self).__post_init__()
super(NumberedObj, self).__post_init__()
print("NamedAndNumbered …Run Code Online (Sandbox Code Playgroud) python multiple-inheritance mixins method-resolution-order python-dataclasses
我对np.isin函数有一个奇怪的问题.如果我创建一个简短的pd.DatetimeIndex,以及该索引中存在的日期:
test_index = pd.date_range(start='2000-01-01', end='2000-01-15',freq='B')
test_date = test_index[0]
Run Code Online (Sandbox Code Playgroud)
我可以检查test_date实际上是索引的第一个元素:
test_date == test_index[0]
True
Run Code Online (Sandbox Code Playgroud)
但是np.isin函数似乎无法识别test_index中的test_date:
np.isin(test_index, test_date)
array([False, False, False, False, False, False, False, False, False,
False])
Run Code Online (Sandbox Code Playgroud)
如果我这样写,就会发生这种情况
np.isin(test_index.values, test_date)
Run Code Online (Sandbox Code Playgroud)
这似乎是错误和奇怪的.test_date和test_index [0]的数据类型以pd.Timestamp的形式给出,它们之间没有明显的区别.任何帮助感激不尽.
我第一次尝试使用多处理并遇到一些相当基本的问题。我下面有一个玩具示例,其中两个进程正在将数据添加到列表中:
def add_process(all_nums_class, numbers_to_add):
for number in numbers_to_add:
all_nums_class.all_nums_list.append(number)
class AllNumsClass:
def __init__(self):
self.all_nums_list = []
all_nums_class = AllNumsClass()
p1 = Process(target=add_process, args=(all_nums_class, [1,3,5]))
p1.start()
p2 = Process(target=add_process, args=(all_nums_class, [2,4,6]))
p2.start()
all_nums_class.all_nums_list
Run Code Online (Sandbox Code Playgroud)
我希望在这些进程之间共享 all_nums_class ,以便它们都可以添加到其 all_nums_list - 所以结果应该是
[1,2,3,4,5,6]
Run Code Online (Sandbox Code Playgroud)
而不是我现在得到的,这只是旧的
[]
Run Code Online (Sandbox Code Playgroud)
有人可以请建议吗?我已经尝试了一下命名空间,但还没有让它在这里工作。
我觉得我最好提及(以防有所不同)我是在 Jupyter 笔记本上执行此操作。
我意识到 np.islcose() 函数可用于安全地检查浮点数是否相等。不过,目前让我感到困惑的是,使用标准 <= 运算符会得到不同的结果。例如:
add_to = 0.05
value64 = np.float64(0.3) + add_to*4
value32 = np.float32(0.3) + add_to*4
threshold = 0.5
print('is close?')
print(np.isclose(value64, threshold))
print(np.isclose(value32, threshold))
print('is less than or equals to?')
print(value64 <= threshold)
print(value32 <= threshold)
Run Code Online (Sandbox Code Playgroud)
给我
is close?
True
True
is less than or equals to?
True
False
Run Code Online (Sandbox Code Playgroud)
有没有人对此有明智的解决方法?我认为一种选择可能是为 numpy 浮点重载 python 比较运算符,并且(在该函数中)将两个浮点数四舍五入到小数点后第 8 位。但这是在速度有些重要的情况下,感觉有点麻烦。
在此先感谢您的帮助!
我有一种情况,我想设置一个带有参数返回类型的函数——下面是一个简化的例子。目前似乎这是不可能的 - 使用什么逻辑习语?如何实现合理的代码重用对我来说并不明显。
struct Output{T <: Number}
other_details::String # lots of stuff here
numeric_output::T
end
function get_output{T <: Number}(input)::Output{T}
transformed_input = input
# Do stuff to transformed_input
Output{T}(
"lots of data",
transformed_input
)
end
input = 1::Int64
get_output{Float64}(input)
Run Code Online (Sandbox Code Playgroud)
任何想法表示赞赏。
我正在处理一些分层数据,这里是一个人为的例子:
data Item a =
Leaf a
| ListItems [Item a]
| DoubleItem (Item a) (Item a)
| TripleItem (Item a) (Item a) (Item a)
Run Code Online (Sandbox Code Playgroud)
我发现自己经常编写这样的代码:
removeDoubles :: Item a -> Item a
removeDoubles x@(Leaf _) = x
removeDoubles (ListItems xs) = ListItems $ removeDoubles <$> xs
removeDoubles (DoubleItem x y) = ListItems [removeDoubles x, removeDoubles y]
removeDoubles (TripleItem x y z) = TripleItem (removeDoubles x) (removeDoubles y) (removeDoubles z)
removeTriples :: Item a -> Item a
removeTriples x@(Leaf _) …Run Code Online (Sandbox Code Playgroud)