我正在使用Python(2.7.4)中的切片:
class Foo():
def __getitem__(self, key):
# Single value
if isinstance(key, (int,long)):
return key
# Slice
if isinstance(key, slice):
print 'key.start = 0x{0:X} key.stop = 0x{1:X}'.format(key.start, key.stop)
length = key.stop - key.start
return str(length)
Run Code Online (Sandbox Code Playgroud)
一切似乎按预期工作:
>>> f = Foo()
>>>
>>> f[42]
42
>>>
>>> f[20:30]
key.start = 0x14 key.stop = 0x1E
'10'
Run Code Online (Sandbox Code Playgroud)
除了切片索引似乎限制为0x7FFFFFFF:
>>> f[0xFEDCBA98 : 0xFFFFFFFF]
key.start = 0x7FFFFFFF key.stop = 0x7FFFFFFF
'0'
>>> f[0x80000000:0x90000000]
key.start = 0x7FFFFFFF key.stop = 0x7FFFFFFF
'0'
Run Code Online (Sandbox Code Playgroud)
为什么切片索引不会long与常规int值进行相同的整数提升?这有什么解决方法吗?
在这篇文章中,Guido van Rossum说功能调用可能很昂贵,但我不明白为什么也不贵.
多少延迟会为您的代码添加一个简单的函数调用,为什么?
我知道cPython有一个GIL,因此如果不使用多处理模块,您的脚本就无法在多个内核上运行.但有没有什么可以阻止内置功能,如使用多核进行排序?我不明白cPython结构,但我认为我问的问题是'内置函数,如sort,any和list comprehension实际上在GIL之下?
这是一个CPython程序,试图用空的初始化解释器sys.path:
#include <Python.h>
int main(int argc, char** argv)
{
wchar_t* program = NULL;
wchar_t* sys_path = NULL;
Py_NoSiteFlag = 1;
program = Py_DecodeLocale(argv[0], NULL);
Py_SetProgramName(program);
sys_path = Py_DecodeLocale("", NULL);
Py_SetPath(sys_path);
Py_Initialize();
PyMem_RawFree(program);
PyMem_RawFree(sys_path);
Py_Finalize();
}
Run Code Online (Sandbox Code Playgroud)
执行上述程序会引发以下错误:
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Current thread 0x00007ffff7fc6700 (most recent call first):
Signal: SIGABRT (Aborted)
Run Code Online (Sandbox Code Playgroud)
那么除了encodings包之外,Python 3.5标准库中的哪些包和模块是运行Python 3.5解释器所必需的?在我的文档中似乎没有这些信息.
python python-embedding python-3.x python-internals python-3.5
当我们使用时,我们的代码需要10分钟来虹吸68,000条记录:
new_file = new_file + line + string
Run Code Online (Sandbox Code Playgroud)
但是,当我们执行以下操作时,只需1秒钟:
new_file += line + string
Run Code Online (Sandbox Code Playgroud)
这是代码:
for line in content:
import time
import cmdbre
fname = "STAGE050.csv"
regions = cmdbre.regions
start_time = time.time()
with open(fname) as f:
content = f.readlines()
new_file_content = ""
new_file = open("CMDB_STAGE060.csv", "w")
row_region = ""
i = 0
for line in content:
if (i==0):
new_file_content = line.strip() + "~region" + "\n"
else:
country = line.split("~")[13]
try:
row_region = regions[country]
except KeyError:
row_region = "Undetermined"
new_file_content += …Run Code Online (Sandbox Code Playgroud) 我注意到一个小的重构产生了一个奇怪的性能损失,它通过max在递归函数内调用内置函数来替换一个循环.
这是我可以制作的最简单的复制品:
import time
def f1(n):
if n <= 1:
return 1
best = 0
for k in (1, 2):
current = f1(n-k)*n
if current > best:
best = current
return best
def f2(n):
if n <= 1:
return 1
return max(f2(n-k)*n for k in (1, 2))
t = time.perf_counter()
result1 = f1(30)
print('loop:', time.perf_counter() - t) # 0.45 sec
t = time.perf_counter()
result2 = f2(30)
print('max:', time.perf_counter() - t) # 1.02 sec
assert result1 == result2
Run Code Online (Sandbox Code Playgroud)
两者 …
显然删除字典中的条目不会触发任何调整大小.只有在添加条目后才会触发调整大小.
这可以从以下内容中看出:
# Drastic example, nobody does such
# things with dicts FWIK
from sys import getsizeof
d = {i:i for i in range(100)}
print(getsizeof(d)) # 4704
for i in range(100):
del d[i] # similarly with pop
print(getsizeof(d)) # 4704
d[0] = 1 # triggers resize
Run Code Online (Sandbox Code Playgroud)
以及关于SO的问题(来自我发现的).set它的行为方式类似,预计会与dicts的行为一致.
list另一方面,当新大小变为已分配的大小的一半时,调整大小; 这在list_resize评论中说明:
/* Bypass realloc() when a previous overallocation is large enough
to accommodate the newsize. If the newsize falls lower than half
the allocated …Run Code Online (Sandbox Code Playgroud) 如果这是一个愚蠢的问题,请提前道歉,但我似乎无法理解以下内容
所以我理解:
逻辑行的结尾由令牌NEWLINE表示
这意味着定义Python语法的方式是结束逻辑行的唯一方法是使用\n令牌.
物理线也是如此(相当于EOL,这是您在编写文件时使用的平台的EOL,但仍然\n通过Python 转换为通用.
逻辑行可以或不可以等同于一个或多个物理行,但通常它是一个,并且大多数情况下,如果您编写干净的代码,它就是一个.
在某种意义上说:
foo = 'some_value' # 1 logical line = 1 physical
foo, bar, baz = 'their', 'corresponding', 'values' # 1 logical line = 1 physical
some_var, another_var = 10, 10; print(some_var, another_var); some_fn_call()
# the above is still still 1 logical line = 1 physical line
# because ; is not a terminator per se but a delimiter
# since Python doesn't use EBNF exactly but rather …Run Code Online (Sandbox Code Playgroud) 我无法理解以下行为.我正在创建2个字符串,并使用is运算符来比较它.在第一种情况下,它的工作方式不同.在第二种情况下,它按预期工作.我使用逗号或空格的原因是什么,它False与比较is时显示,当没有使用逗号,空格或其他字符时,它给出True
Python 3.6.5 (default, Mar 30 2018, 06:41:53)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'string'
>>> b = a
>>> b is a
True
>>> b = 'string'
>>> b is a
True
>>> a = '1,2,3,4'
>>> b = a
>>> b is a
True
>>> b = '1,2,3,4'
>>> b is a
False
Run Code Online (Sandbox Code Playgroud)
有关python以不同方式解释字符串的原因的可靠信息吗?我最初理解,a并b指同一个对象.然后说 …
我正在玩f字符串(请参阅PEP 498),因此我决定检查f字符串解析(例如f“ {1}”)的速度与通常的str解析(例如str(1) ))。但是令我惊讶的是,当我使用timeit函数检查两种方法的速度时,我发现
>>> from timeit import timeit
>>> timeit("f'{1}'")
0.1678762999999961
Run Code Online (Sandbox Code Playgroud)
而
>>> timeit("str(1)")
0.3216999999999999
Run Code Online (Sandbox Code Playgroud)
甚至是repr func,在大多数情况下,它们都比str转换快
>>> timeit("repr(1)")
0.2528296999999995
Run Code Online (Sandbox Code Playgroud)
我不知道为什么呢?我以为f弦在内部调用了str,但是现在,我有点困惑了,有什么想法吗?提前致谢!
PD:就像有人想知道的那样:
assert f"{1}" == str(1) == repr(1)
Run Code Online (Sandbox Code Playgroud) python ×10
python-internals ×10
python-3.x ×5
cpython ×2
bnf ×1
dictionary ×1
f-string ×1
identity ×1
performance ×1
profiling ×1
python-2.7 ×1
python-3.5 ×1
python-3.6 ×1
string ×1