我想采样~10?来自约 10 人的次数?没有替换和权重的整数,每次选择 10 个元素。每次采样后,我都会改变权重。我在以下脚本中为两种方法(python3 和 numpy)计时。这两种方法对我来说似乎都非常缓慢,你有没有办法加快速度?
import numpy as np
import random
@profile
def test_choices():
population = list(range(10**7))
weights = np.random.uniform(size=10**7)
np_weights = np.array(weights)
def numpy_choice():
np_w = np_weights / sum(np_weights)
c = np.random.choice(population, size=10, replace=False, p=np_w)
def python_choice():
c = []
while len(c) < 10:
c += random.choices(population=population, weights=weights, k=10 - len(c))
c = list(set(c))
for i in range(10**1):
numpy_choice()
python_choice()
add_weight = np.random.uniform()
random_element = random.randint(0, 10**7)
weights[random_element] += add_weight
np_weights[random_element] += add_weight
test_choices()
Run Code Online (Sandbox Code Playgroud)
随着计时器结果:
Line # …Run Code Online (Sandbox Code Playgroud) 我正在使用 Django 模型创建 PostgreSQL-DB。我有一个 DateTimeField,我想将当前时间戳设置为默认值。我知道有多个消息来源建议如何做到这一点。但是,当我在 Django 之外检查数据库时,默认时间戳不会显示。
我尝试过的方法:
1.
created_at = models.DateTimeField(auto_now_add=True)
Run Code Online (Sandbox Code Playgroud)
from django.db.models.functions import Now
...
created_at = models.DateTimeField(default=Now())
Run Code Online (Sandbox Code Playgroud)
from django.utils.timezone import now
...
created_at = models.DateTimeField(default=now)
Run Code Online (Sandbox Code Playgroud)
我期望 PostgreSQL 数据库显示:
TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
它显示的timestamp with time zone not null只是没有默认值。任何关于如何做到这一点的想法将不胜感激。
我有一个关于 python 中列表的内存使用情况的假设问题。我有一个很长的列表my_list,如果加载到内存中,它会消耗多个千兆字节。我想循环该列表并在迭代期间仅使用每个元素一次,这意味着我可以在循环它们后从列表中删除它们。当我循环时,我正在内存中存储其他内容,这意味着我分配的内存my_list现在需要用于其他内容。因此,理想情况下,我想在循环遍历列表元素时删除列表元素并释放内存。
I assume, in most cases, a generator would make the most sense here. I could dump my list to a csv file and then read it line by line in a for-loop. In that case, my_list would never be loaded into memory in the first place. However, let's assume for the sake of discussion I don't want to do that.
Is there a way of releasing the memory of a list as I …
作为查询的结果,我收到一个迭代器,其中每行都有两个键“x”和“y”。我想从所有行中提取一个包含 x 元素和 y 元素的列表。
示例数据:
data = ({"x": 1, "y": -1}, {"x": 2, "y": -2}, {"x": 3, "y": -3})
Run Code Online (Sandbox Code Playgroud)
我想要的是:
x = [1, 2, 3]
y = [-1, -2, -3]
Run Code Online (Sandbox Code Playgroud)
现在我可以做一个 for 循环:
x, y = [], []
for row in data:
x.append(row["x"])
y.append(row["y"])
Run Code Online (Sandbox Code Playgroud)
或者像这样:
x, y = [b[0] for b in [list(a.values()) for a in data]], [b[1] for b in [list(a.values()) for a in data]]
Run Code Online (Sandbox Code Playgroud)
但在我看来,应该有一种更优雅、更直接的方式来做到这一点,而我没有看到。有什么建议?