我在Python中有两个迭代,我想成对地遍历它们:
foo = (1, 2, 3)
bar = (4, 5, 6)
for (f, b) in some_iterator(foo, bar):
print "f: ", f, "; b: ", b
Run Code Online (Sandbox Code Playgroud)
它应该导致:
f: 1; b: 4
f: 2; b: 5
f: 3; b: 6
Run Code Online (Sandbox Code Playgroud)
一种方法是迭代索引:
for i in xrange(len(foo)):
print "f: ", foo[i], "; b: ", b[i]
Run Code Online (Sandbox Code Playgroud)
但这对我来说似乎有点不合时宜.有没有更好的方法呢?
我正在尝试在while循环中计时while循环,执行所需的总时间,并记录每次循环所需的时间.如果可能的话,我需要一种方法来使用我的代码实现这一点,或者开放我可能还不知道的不同概念.
import random
import time
import sys
def main():
looperCPU = 500
start = time.time()
while (looperCPU != 0):
#start = time.time()
#this is the computation for 3 secs
time.sleep(3)
random_number = random.randint(0,1000)
#Send to printer for processing
#.75 secs to 4.75 secs to generate a pause before printing
secondsPause = random.uniform(.75,4.75)
#This is the printer function
printerLooper = True
while printerLooper == True :
print("Sleeping for ", secondsPause, " seconds")
print(random_number)
printerLooper = False
#
print("total time taken this …
Run Code Online (Sandbox Code Playgroud) 如果b是2x2 np.ndarray并且执行了以下赋值,numpy在后台执行什么操作,即它是否首先将列表[100,100]转换为numpy数组,还是直接使用列表[100,100]来执行填写b第一行的值:
b[1,:] = [100,100]
Run Code Online (Sandbox Code Playgroud)
我可以在文档中的哪个位置找到更多相关信息?
我试图根据需要全部满足的条件列表选择DataFrame的行。这些条件存储在字典中,格式为{column:max-value}。
这是一个例子: dict = {'name': 4.0, 'sex': 0.0, 'city': 2, 'age': 3.0}
我需要选择相应属性小于或等于字典中相应值的所有DataFrame行。
我知道要基于两个或多个条件选择行,我可以这样写:
rows = df[(df[column1] <= dict[column1]) & (df[column2] <= dict[column2])]
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何以Python方式选择与字典中存在的条件匹配的行?我尝试过这种方式
keys = dict.keys()
rows = df[(df[kk] <= dict[kk]) for kk in keys]
Run Code Online (Sandbox Code Playgroud)
但这给了我一个错误=“ [ expected
”,即使放置[
符号也不会消失。
我需要在可变数量的数据上计时函数的执行时间。
def foo(raw_data):
preprocessed_data = preprocess_data(raw_data)
time = timeit.Timer('module.expensive_func(preprocessed_data)', 'import module').timeit()
Run Code Online (Sandbox Code Playgroud)
但是,preprocessed_data
不是全局变量。无法使用导入from __main__
。它在此子例程中是本地的。
如何导入data
到timeit.Timer
环境中?
TL; DR
使用可变维度键实现字典过滤功能的最有效方法是什么?过滤器应采用与字典键相同尺寸的元组,并输出字典中与过滤器匹配的所有键,以便filter[i] is None or filter[i] == key[i]
适用于所有维度i
.
在我目前的项目中,我需要处理包含大量数据的字典.字典的一般结构是这样的,它包含2到4个整数作为键和整数作为值的元组.字典中的所有键具有相同的尺寸.为了说明,以下是我需要处理的字典示例:
{(1, 2): 1, (1, 5): 2}
{(1, 5, 3): 2}
{(5, 2, 5, 2): 8}
Run Code Online (Sandbox Code Playgroud)
这些词典包含大量条目,其中最大的条目大约有20 000个条目.我经常需要过滤这些条目,但通常只查看关键元组的某些索引.理想情况下,我想要一个我可以提供过滤器元组的功能.然后该函数应返回与过滤器元组匹配的所有键.如果过滤器元组包含一个None
条目,那么这将匹配该索引处字典的关键元组中的任何值.
函数应该对具有二维键的字典执行的操作的示例:
>>> dict = {(1, 2): 1, (1, 5): 2, (2, 5): 1, (3, 9): 5}
>>> my_filter_fn((1, None))
{(1, 2), (1, 5)}
>>> my_filter_fn((None, 5))
{(1, 5), (2, 5)}
>>> my_filter_fn((2, 4))
set()
>>> my_filter_fn((None, None))
{(1, 2), (1, 5), (2, 5), (3, 9)}
Run Code Online (Sandbox Code Playgroud)
由于我的词典具有不同的元组维度,我尝试通过编写生成器表达式来解决这个问题,该表达式考虑了元组的维度:
def …
Run Code Online (Sandbox Code Playgroud) 来自Python文档re.compile()
:
注意传递给re.match(),re.search()或re.compile()的最新模式的编译版本被缓存,因此一次只使用几个正则表达式的程序不必担心定期编译表达式.
但是,在我的测试中,这个断言似乎没有成功.在对重复使用相同模式的以下片段进行计时时,编译版本仍然比未编译版本(应该被缓存)快得多.
我在这里找不到能解释时差的东西吗?
import timeit
setup = """
import re
pattern = "p.a.t.t.e.r.n"
target = "p1a2t3t4e5r6n"
r = re.compile(pattern)
"""
print "compiled:", \
min(timeit.Timer("r.search(target)", setup).repeat(3, 5000000))
print "uncompiled:", \
min(timeit.Timer("re.search(pattern, target)", setup).repeat(3, 5000000))
Run Code Online (Sandbox Code Playgroud)
结果:
compiled: 2.26673030059
uncompiled: 6.15612802627
Run Code Online (Sandbox Code Playgroud) 链接主题(但不重复):装饰器对代码的特定行而不是整个方法进行计时?
我知道装饰器通常如何用于 Python 函数。
单行代码是否有类似的概念/语法?
示例:与
def measuretime(lineofcode):
start = time.time()
lineofcode()
print time.time() - start
Run Code Online (Sandbox Code Playgroud)
然后
@measuretime
im = Image.open(BytesIO(base64.b64decode(data)))
Run Code Online (Sandbox Code Playgroud)
会被解释为
start = time.time()
im = Image.open(BytesIO(base64.b64decode(data)))
print time.time() - start
Run Code Online (Sandbox Code Playgroud)
笔记:
我知道像这样测量执行时间并不是最佳的,最好使用timeit
等等,但这只是一个随机示例来展示我正在寻找的内容(单行代码的装饰器)
我正在寻找 1 或 2 行代码解决方案(当然还有函数的定义)。如果解决方案需要超过 2 行代码(即超过类似的代码@measuretime
),那么最好放弃并执行正常操作:
start = time.time()
im = Image.open(BytesIO(base64.b64decode(data)))
print time.time() - start
Run Code Online (Sandbox Code Playgroud)
我在WingIDE 101(版本4)的Windows 7操作系统上运行Python 3.2.在这种情况下环境并不重要,但我认为我应该具体.
我的代码如下.它不是最佳的,只是找到素数的一种方法:
def isPrime2(n):
if n == 1:
return False
count = 0
for i in range(2,n+1,2):
if n%i == 0:
count = count + 1
if count > 2:
return False
for i in range(1,n+1,2):
if n%i == 0:
count = count + 1
if count > 2:
return False
if count == 2:
return True
start = time.time()
x = isPrime2(571)
end = time.time()
time_interval = end - start
print("%1.15f"%time_interval)
print(x)
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是time.time()函数似乎不是时间.当我运行这个程序时,我得到了
0.000000000000000
True
Run Code Online (Sandbox Code Playgroud)
我也尝试了这个最多30位数,所有这些都保持为零. …
在我的小项目中,我按降序排列了一个列表,但是,我的目标是在此自定义模式中对其进行排序.(最大 - >最小 - >次最大 - >次最小 - >)等.
在java中,我能够这样做:
public static void wackySort(int[] nums) {
//first, this simply sorts the array by ascending order.
int sign = 0;
int temp = 0;
int temp2 = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length -1; j++){
if (nums[j] > nums[j+1]) {
temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
//prepare for new array to actually …
Run Code Online (Sandbox Code Playgroud) python ×11
performance ×3
dictionary ×2
time ×2
timeit ×2
decorator ×1
filtering ×1
for-loop ×1
iterator ×1
list ×1
namespaces ×1
numpy ×1
pandas ×1
python-2.7 ×1
regex ×1
semantics ×1
while-loop ×1