我最近比较的性能collections.Counter来sorted进行比较检查(如果有的迭代包含具有相同数量相同的元素),并同时的大迭代表现Counter一般优于sorted它的短iterables慢得多.
使用line_profiler的瓶颈似乎是isinstance(iterable, collections.Mapping)在-check Counter.update:
%load_ext line_profiler # IPython
lst = list(range(1000))
%lprun -f Counter.update Counter(lst)
Run Code Online (Sandbox Code Playgroud)
给我:
Timer unit: 5.58547e-07 s
Total time: 0.000244643 s
File: ...\lib\collections\__init__.py
Function: update at line 581
Line # Hits Time Per Hit % Time Line Contents
==============================================================
581 def update(*args, **kwds):
601 1 8 8.0 1.8 if not args:
602 raise TypeError("descriptor 'update' of 'Counter' object "
603 "needs an argument")
604 …Run Code Online (Sandbox Code Playgroud) 我是 python 的新手,所以我习惯使用array[i][j]而不是array[i,j]. 今天,我按照教程创建的脚本不起作用,直到我发现我正在使用
numpy.dot(P[0][:], Q[:][0])
Run Code Online (Sandbox Code Playgroud)
代替
numpy.dot(P[0,:], Q[:,0])
Run Code Online (Sandbox Code Playgroud)
出于某种原因,第二个有效,而第一个给了我一个形状错误。矩阵维度是 MxK 和 KxN。
我试图同时打印P[0][:]和P[0,:]运行id(),type()并且P[0][:].shape,也没有找到一个理由吧。为什么这些东西不一样?
我在 Jupyter Notebook 4.3.0 和 Python 2.7.13 上运行它。
我有一个日期列表,目标是计算每个日期的出现次数,同时保持它们在原始列表中的显示顺序.请考虑以下示例:
该列表only_dates如下所示:
[datetime.date(2017, 3, 9), datetime.date(2017, 3, 10), datetime.date(2017, 3, 10), datetime.date(2017, 3, 11)]
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用groupby:
import itertools
day_wise_counts = [(k, len(list(g))) for k, g in itertools.groupby(only_dates)]
print(str(day_wise_counts))
Run Code Online (Sandbox Code Playgroud)
这打印
[(datetime.date(2017, 3, 10), 1), (datetime.date(2017, 3, 9), 1), (datetime.date(2017, 3, 10), 1), (datetime.date(2017, 3, 11), 1)]
Run Code Online (Sandbox Code Playgroud)
我理解这种情况正在发生,因为最终每个日期对象在分组时被视为不同的日期对象.
我期待输出为:
[(datetime.date(2017, 3, 9), 1), (datetime.date(2017, 3, 10), 2), (datetime.date(2017, 3, 11), 1)]
Run Code Online (Sandbox Code Playgroud)
我不一定在寻找元组列表.只要保持原始日期顺序,字典输出也就足够了.(OrderedDict也许).
我怎样才能做到这一点?
更新:有可能建议多种方法都能正常运行.但我应该提到我将为大量数据执行此操作.因此,如果您的解决方案在运行时间方面是最佳的,那就太好了.如果可以,请相应地编辑您的答案/评论.
更新2:数据大小可以达到100万行.
我想通过使用内存视图来加速我的代码。这是我使用的两个类:
cdef class child:
cdef public int[:] move
def __init__(self, move):
self.move = move
cdef class parent:
cdef public:
list children
int[:, :] moves
def __init__(self):
self.children = []
def add_children(self, moves):
cdef int i = 0
cdef int N = len(moves)
for i in range(N):
self.children.append(child(moves[i]))
Run Code Online (Sandbox Code Playgroud)
这是我想检查类是否有效的代码:
temp = []
for i in range(100):
temp.append([i, i+1])
cdef int[:, :] moves = np.asarray(temp, dtype=np.int32)
a = parent()
a.add_children(moves)
for move in moves:
for ch in a.children:
if move == ch.move: …Run Code Online (Sandbox Code Playgroud) 当我尝试在迭代其元素时更新集合时,它的行为应该是什么?
我在各种场景中尝试过它并且它不会迭代迭代开始后添加的元素以及迭代期间删除的元素.如果我在迭代期间删除并放回任何元素,则会考虑该元素.什么是确切的行为,它是如何工作的?
这将打印字符串的所有排列:
def permutations(s):
ans = []
def helper(created, remaining):
if len(created) == len(s):
ans.append(''.join(created))
return
for ch in remaining:
remaining.remove(ch)
created.append(ch)
helper(created, remaining)
remaining.add(ch)
created.pop()
helper([], set(s))
return ans
Run Code Online (Sandbox Code Playgroud)
这里的行为是不可预测的,有时e是打印的,有时则不是:
ab = set(['b','c','d'])
x = True
for ch in ab:
if x:
ab.remove('c')
ab.add('e')
x = False
print(ch)
Run Code Online (Sandbox Code Playgroud)
在这里,我总是'c'只看到一次.即使第一个字符是'c':
ab = set(['b','c','d'])
x = True
for ch in ab:
if x:
ab.remove('c')
ab.add('c')
x = False
print(ch)
Run Code Online (Sandbox Code Playgroud)
以及实现上述功能相同目标的另一种方法:
def permwdups(s):
ans = …Run Code Online (Sandbox Code Playgroud) 在另一个Q + A(我可以在pandas中执行动态cumsum?)我对使用prange这个代码的正确性做了评论(这个答案):
from numba import njit, prange
@njit
def dynamic_cumsum(seq, index, max_value):
cumsum = []
running = 0
for i in prange(len(seq)):
if running > max_value:
cumsum.append([index[i], running])
running = 0
running += seq[i]
cumsum.append([index[-1], running])
return cumsum
Run Code Online (Sandbox Code Playgroud)
评论是:
我不建议并行化一个不纯的循环.在这种情况下,
running变量使其不纯.有4种可能的结果:(1)numba决定它不能并行处理它只是处理循环cumsum而不是prange(2)它可以将变量提升到循环之外并在余数上使用并行化(3)numba错误地插入并行执行和结果之间的同步可能是虚假的(4)numba在运行时插入必要的同步,这可能会比通过并行化首先获得更多的开销
而后来的补充:
当然,
running和cumsum变量都使循环"不纯",而不仅仅是前面评论中所述的运行变量
然后我被问到:
这可能听起来像一个愚蠢的问题,但我怎么能弄清楚它做了哪4件事并改进了呢?我真的想用numba变得更好!
鉴于它可能对未来的读者有用,我决定在这里创建一个自我回答的Q + A. 掠夺者:我无法真正回答4个结果中的哪一个产生的问题(或者如果numba产生完全不同的结果),所以我非常鼓励其他答案.
我试图以某种方式获得部分方法工作的文档。我目前的代码是
from functools import partialmethod
class Fun(object):
def test(self, num):
"""
I have a documentation
"""
return num
test2 = partialmethod(test, num=10)
test2.__doc__ = """Blub"""
test3 = partialmethod(test, num=20)
Run Code Online (Sandbox Code Playgroud)
但如果我跑
a = Fun()
a.test2.__doc__ # only returns the partials documentation not "Blub"
Fun.test2.__doc__ # gives nothing
Run Code Online (Sandbox Code Playgroud)
和 Sphinx 使用autoclassas列出它们undocumented members。
我已阅读https://docs.python.org/3/library/functools.html#partial-objects和https://docs.python.org/3/library/functools.html#functools.partialmethod但这是否意味着有没有办法让单证到partialmethods的还是我只是太傻呢?
PEP 424在“理由”中提到:
能够根据预期大小(由 估计)来预分配列表
__length_hint__可能是一项重大优化。据观察,CPython 运行某些代码的速度比 PyPy 更快,这纯粹是因为存在这种优化。
所以我问自己现在在这里问的问题:基于这些知识是否可以加快某些可迭代类处理迭代器的速度(当可以正确预测它的“长度”时)?
在使用scipy/numpy时,我确实获得了存储到的信息 numpy.ndarray
>>> a
array([[ 0.15555605, 0.51031528, 0.84580176, 0.06722675],
[ 0.60556045, 0.62721023, -0.48979983, -0.04152777],
[-0.78044785, 0.58837543, -0.21146041, -0.13568023],
[ 0. , 0. , 0. , 1. ]])
>>> print(a)
[[ 0.15555605 0.51031528 0.84580176 0.06722675]
[ 0.60556045 0.62721023 -0.48979983 -0.04152777]
[-0.78044785 0.58837543 -0.21146041 -0.13568023]
[ 0. 0. 0. 1. ]]
Run Code Online (Sandbox Code Playgroud)
如何在一行上打印结果?
我已经检查过:
>>> numpy.get_printoptions()
{'precision': 8, 'threshold': 1000, 'edgeitems': 3, 'linewidth': 75, 'suppress': False, 'nanstr': 'nan', 'infstr': 'inf', 'formatter': None}
Run Code Online (Sandbox Code Playgroud)
但即使设置linewidth为1000也不会改变这一点.有没有办法更改该类型的显示格式?
是否也可以在每个数字之间添加逗号(如数组显示但没有周围array(...))?
所以我的 python 代码中遇到了一个问题,我将其归结为:
假设我们有一个函数u:
def u(y,t):
h = float(10)
U0 = float(1)
return U0/h*(y)
Run Code Online (Sandbox Code Playgroud)
和一个数组:
a=np.array([[0]*2]*2)
Run Code Online (Sandbox Code Playgroud)
然后执行以下操作:
a[1][1] = u(1,0)
Run Code Online (Sandbox Code Playgroud)
但尽管等于 仍会a[1][1]返回。0u(1,0)0.1
为什么会发生这种情况以及如何避免这种情况?