有没有办法在SQL查询中使用可变长度占位符?
现在有一个3元组,我写这样的东西:
c.execute('SELECT * FROM table WHERE word IN (?, ?, ?)', tup)
Run Code Online (Sandbox Code Playgroud)
但是,如果tup可以有不同的长度,也许是4元组或2元组怎么办?在这种情况下是否有使用占位符的语法?如果没有,编写代码的首选方法是什么?
我想知道是否有一种简单的方法可以在Python中构建一个可索引的弱有序集.我试着自己建一个.这是我想出的:
"""
An indexable, ordered set of objects, which are held by weak reference.
"""
from nose.tools import *
import blist
import weakref
class WeakOrderedSet(blist.weaksortedset):
"""
A blist.weaksortedset whose key is the insertion order.
"""
def __init__(self, iterable=()):
self.insertion_order = weakref.WeakKeyDictionary() # value_type to int
self.last_key = 0
super().__init__(key=self.insertion_order.__getitem__)
for item in iterable:
self.add(item)
def __delitem__(self, index):
values = super().__getitem__(index)
super().__delitem__(index)
if not isinstance(index, slice):
# values is just one element
values = [values]
for value in values:
if value …Run Code Online (Sandbox Code Playgroud) 我有一个日期排序列表:(有日间隔)
list_of_dts = [
datetime.datetime(2012,1,1,0,0,0),
datetime.datetime(2012,1,1,1,0,0),
datetime.datetime(2012,1,2,0,0,0),
datetime.datetime(2012,1,3,0,0,0),
datetime.datetime(2012,1,5,0,0,0),
]
Run Code Online (Sandbox Code Playgroud)
而且我想将它们分成每天的列表:
result = [
[datetime.datetime(2012,1,1,0,0,0), datetime.datetime(2012,1,1,1,0,0)],
[datetime.datetime(2012,1,2,0,0,0)],
[datetime.datetime(2012,1,3,0,0,0)],
[], # Empty list for no datetimes on day
[datetime.datetime(2012,1,5,0,0,0)]
]
Run Code Online (Sandbox Code Playgroud)
在算法上,应该可以实现至少O(n).
也许类似于以下内容:(这显然不会处理错过的日子,并且丢弃最后的dt,但这是一个开始)
def dt_to_d(list_of_dts):
result = []
start_dt = list_of_dts[0]
day = [start_dt]
for i, dt in enumerate(list_of_dts[1:]):
previous = start_dt if i == 0 else list_of_dts[i-1]
if dt.day > previous.day or dt.month > previous.month or dt.year > previous.year:
# split to new sub-list
result.append(day)
day = []
# Loop for …Run Code Online (Sandbox Code Playgroud) 让我们说你有一套:
foo = {1, 2, 3, 4, 5}
Run Code Online (Sandbox Code Playgroud)
在我正在阅读的书中,Pro Python,它说使用foo.pop()将弹出该选择中的任意数字.但是......当我尝试它时,它pops 1, then 2, then 3...是否随意做,或者这只是巧合?
我有一个双打数组,我想从中选择一个值,每个值被选中的概率与其值成反比.例如:
arr[0] = 100
arr[1] = 200
Run Code Online (Sandbox Code Playgroud)
在这个例子中,元素0将被选中66%,元素1有33%的几率.我编码很困难.到目前为止我所做的是计算数组的总值(例子是300),然后我在计算它们之前使用了反转数字,然后计算总数的百分比.我无法得到任何工作.最后我希望:
new randomNumber
for(int y=0; y < probabilities.length; y++){
if(randomNumber < probabilities[y]){
Select probabilities[y]
}
}
Run Code Online (Sandbox Code Playgroud)
或者那些影响的东西.有帮助吗?编码是用Java编写的,但我可以调整任何伪代码.
我发现了
input('some\x00 text')
Run Code Online (Sandbox Code Playgroud)
将提示some而不是some text.
从消息来源,我发现这个函数使用C函数PyOS_Readline,它在NULL字节后忽略提示中的所有内容.
来自PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, const char *prompt):
fprintf(stderr, "%s", prompt);
Run Code Online (Sandbox Code Playgroud)
https://github.com/python/cpython/blob/3.6/Python/bltinmodule.c#L1989 https://github.com/python/cpython/blob/3.6/Parser/myreadline.c#L251
这是一个错误还是有原因的?
我正在尝试使用该inspect模块,但似乎我不能在内置(本机?)类中使用它,否则我误解了.
我正在使用Python 2.7并尝试使用Python 3.2.
这是有效的:
>>> import inspect
>>> class C:
... def __init__(self,a,b=4):
... self.sum = a + b
...
>>> inspect.getargspec(C.__init__)
ArgSpec(args=['self','a', 'b'], varargs=None, keywords=None, defaults=(4,))
Run Code Online (Sandbox Code Playgroud)
这不起作用:
>>> import inspect
>>> import ast
>>> inspect.getargspec(ast.If.__init__)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 813, in getargspec
raise TypeError('{!r} is not a Python function'.format(func))
TypeError: <slot wrapper '__init__' of '_ast.AST' objects> is not a Python function
Run Code Online (Sandbox Code Playgroud)
我想知道是否有另一种技术可以自动获取这些参数?
(在我的例子中,我想到了一个解析Python语法的替代方案,ASDL文件解释了如何使用我在PyPy Project的源代码中看到的代码来初始化AST节点,但我想知道是否还有其他方法)
我想知道是否calloc()优于a malloc后跟a memset.后者似乎是分配和初始化内存的最常用方式.
一个GitHub的代码搜索变成了许多calloc测试和实现,但在页面的第一个数字代码没有实际使用calloc.
有谁知道任何使用或推荐使用的项目/组织calloc以及推荐它的情况?
从下面的评论和答案中,以下是迄今为止出现的一些想法:
calloc(n, size) 可以防止溢出 malloc(n * size)
结合malloc和memset使calloc有机会请求已知已经归零的页面.
calloc的一个缺点是组合的步骤可能会排除malloc周围的其他包装器.
当我按下按钮时我想重定向,所以我用它withRouter来获取历史道具的访问权限.
但我得到错误:
Uncaught TypeError: Cannot read property 'route' of undefined
at Route.computeMatch (react-router.js:1160)
Run Code Online (Sandbox Code Playgroud)
使用withRouterHOC 包装组件时出错.如果我删除withRouter功能,它只是工作.
我的代码如下所示:
class App extends Component {
// ...some unrelated functions
handleTitleTouchTap = e => {
e.preventDefault()
const { history } = this.props
history.push('/')
}
render() {
//...other components
<Router>
<div>
<Switch>
<Route exact={true} path="/" component={Home} />
<Route path="/search" component={Search}/>
<Route path="/gamelist/:listId" component={GameListDetail}/>
<Route path="/game/:gameId" component={GameDetail}/>
<Route path="/manageuser" component={ManageUser} />
<Route path="/addgamelist" component={AddGameList} />
<Route path="/addgame" component={AddGame} />
<Route path="/test" …Run Code Online (Sandbox Code Playgroud) 我在具有8 GB RAM的macOS上具有4个内核(8线程超线程)的Intel i7并行生成大约400,000,000(4亿)个随机数.
但是,我也在DigitalOcean服务器上生成400,000,000个随机数,Debian上有20个内核,64 GB RAM.
这是代码:
import multiprocessing
import random
rangemin = 1
rangemax = 9
def randomGenPar_backend(backinput):
return random.randint(rangemin, rangemax)
def randomGenPar(num):
pool = multiprocessing.Pool()
return pool.map(randomGenPar_backend, range(0, num))
randNum = 400000000
random.seed(999)
randomGenPar(randNum)
Run Code Online (Sandbox Code Playgroud)
这些是基准测试的结果:
5,000,000 Random Numbers:
1 Core: 5.984
8 Core: 1.982
50,000,000 Random Numbers:
1 Core: 57.28
8 Core: 19.799
20 Core: 18.257
Times Benefit (20 core vs. 8 core) = 1.08
100,000,000 Random Numbers:
1 Core: 115
8 Core: 40.434
20 Core: 31.652 …Run Code Online (Sandbox Code Playgroud) python performance timing multiprocessing python-multiprocessing