小编Sha*_*ger的帖子

Python装饰,自我混淆了

我是Python修饰者的新手(哇,很棒的功能!),我无法让下面的代码工作,因为self参数混淆了.

#this is the decorator
class cacher(object):

    def __init__(self, f):
        self.f = f
        self.cache = {}

    def __call__(self, *args):
        fname = self.f.__name__
        if (fname not in self.cache):
            self.cache[fname] = self.f(self,*args)
        else:
            print "using cache"
        return self.cache[fname]

class Session(p.Session):

    def __init__(self, user, passw):
        self.pl = p.Session(user, passw)

    @cacher
    def get_something(self):
        print "get_something called with self = %s "% self
        return self.pl.get_something()

s = Session(u,p)
s.get_something()
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我得到:

get_something called with self = <__main__.cacher object at 0x020870F0> 
Traceback:
...
AttributeError: 'cacher' …
Run Code Online (Sandbox Code Playgroud)

python python-decorators

17
推荐指数
1
解决办法
5355
查看次数

Python:在字符串列表中优化搜索子字符串

我有一个特殊的问题,我想在许多字符串列表中搜索许多子字符串.以下是我要做的事情的要点:

listStrings = [ACDE, CDDE, BPLL, ... ]

listSubstrings = [ACD, BPI, KLJ, ...]
Run Code Online (Sandbox Code Playgroud)

以上条目仅是示例.len(listStrings)是~60,000,len(listSubstrings)是~50,000-300,000,len(listStrings [i])是10到30,000.

我目前的Python尝试是:

for i in listSubstrings:
   for j in listStrings:
       if i in j:
          w.write(i+j)
Run Code Online (Sandbox Code Playgroud)

或者沿着这些方向的东西.虽然这对我的任务起作用,但速度非常慢,使用一个核心并按照40分钟的顺序完成任务.有没有办法加快速度?

我不相信我可以用listStrings:listSubstrings制作一个dict,因为有可能需要在两端存储重复的条目(尽管我可以尝试这个,如果我能找到一种方法来附加一个唯一的标签每一个,因为dicts是如此快得多).同样,我认为我不能预先计算可能的子串.我甚至不知道搜索dict键是否比搜索列表更快(因为dict.get()它将提供特定输入而不是寻找子输入).在内存中搜索列表是否相对较慢?

python substring string-matching

17
推荐指数
2
解决办法
3594
查看次数

iter(可调用,哨兵)的用途是什么?

所以,我正在观看Raymond Hettinger的演讲,将代码转换为美丽的,惯用的Python,并且他提出了iter我从未意识到的这种形式.他的例子如下:

代替:

blocks = []
while True:
    block = f.read(32)
    if block == '':
        break
    blocks.append(block)
Run Code Online (Sandbox Code Playgroud)

使用:

blocks = []
read_block = partial(f.read, 32)
for block in iter(read_block, ''):
    blocks.append(block)
Run Code Online (Sandbox Code Playgroud)

检查完文档iter,我发现了一个类似的例子:

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)
Run Code Online (Sandbox Code Playgroud)

这看起来对我很有用,但我想知道你是否Pythonistas知道这个构造的任何不涉及I/O读取循环的例子?也许在标准库中?

我可以想到非常人为的例子,如下所示:

>>> def f():
...     f.count += 1
...     return f.count
... 
>>> f.count = 0
>>> list(iter(f,20))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …
Run Code Online (Sandbox Code Playgroud)

python

17
推荐指数
3
解决办法
3571
查看次数

Floras16比keras中的float32慢

我正在测试我的新NVIDIA Titan V,它支持float16操作.我注意到在训练期间,float16比float32(~500 ms /步)慢得多(~800 ms /步).

要执行float16操作,我将keras.json文件更改为:

{
"backend": "tensorflow",
"floatx": "float16",
"image_data_format": "channels_last",
"epsilon": 1e-07
}
Run Code Online (Sandbox Code Playgroud)

为什么float16操作这么慢?我是否需要修改我的代码而不仅仅是keras.json文件?

我在Windows 10上使用CUDA 9.0,cuDNN 7.0,tensorflow 1.7.0和keras 2.1.5.我的python 3.5代码如下:

img_width, img_height = 336, 224

train_data_dir = 'C:\\my_dir\\train'
test_data_dir = 'C:\\my_dir\\test'
batch_size=128

datagen = ImageDataGenerator(rescale=1./255,
    horizontal_flip=True,   # randomly flip the images 
    vertical_flip=True) 

train_generator = datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_height, img_width),
    batch_size=batch_size,
    class_mode='binary')

test_generator = datagen.flow_from_directory(
    test_data_dir,
    target_size=(img_height, img_width),
    batch_size=batch_size,
    class_mode='binary')

# Architecture of NN
model = Sequential()
model.add(Conv2D(32,(3, 3), input_shape=(img_height, img_width, 3),padding='same',kernel_initializer='lecun_normal'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32,(3, …
Run Code Online (Sandbox Code Playgroud)

python keras tensorflow

17
推荐指数
1
解决办法
4509
查看次数

带有readlines()方法的Python3 UnicodeDecodeError

试图创建一个读取行并发布它们的twitter机器人.使用Python3和tweepy,通过我的共享服务器空间上的virtualenv.这是代码中似乎有问题的一部分:

#!/foo/env/bin/python3

import re
import tweepy, time, sys

argfile = str(sys.argv[1])

filename=open(argfile, 'r')
f=filename.readlines()
filename.close()
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xfe in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

该错误特别指向错误f=filename.readlines()的来源.知道什么可能是错的吗?谢谢.

python unicode sys tweepy python-3.x

16
推荐指数
3
解决办法
2万
查看次数

Python是,==运算符优先级

在Python3中,

a = b = 3
a is None == b is None
Run Code Online (Sandbox Code Playgroud)

返回False,但是

(a is None) == (b is None)
Run Code Online (Sandbox Code Playgroud)

返回True.所以我假设仅基于这个例子,==优先于is.

然而,

a = b = None
a is None == b is None
Run Code Online (Sandbox Code Playgroud)

返回True.和

(a is None) == (b is None)
Run Code Online (Sandbox Code Playgroud)

返回True.但

a is (None == b) is None
Run Code Online (Sandbox Code Playgroud)

返回False.在这种情况下,它会看起来好像就是有优先==.

再举一个例子,这个表达并不意味着什么,但请耐心等待.如果我说

None is None == None
Run Code Online (Sandbox Code Playgroud)

它返回True.但是以下两个都返回False.

None is (None == None)
(None is None) == None
Run Code Online (Sandbox Code Playgroud)

很明显,Python并没有用一些严格的优先级来评估它们,但是我很困惑发生了什么.如何用2个不同的运算符来评估这个表达式,但是不同于任何一个运算符?

python operator-precedence python-3.x nonetype

15
推荐指数
1
解决办法
303
查看次数

如何通过python打开文件

我是编程和python语言的新手.

我知道如何在python中打开文件,但问题是我如何打开文件作为函数的参数?

例:

function(parameter)
Run Code Online (Sandbox Code Playgroud)

这是我写出代码的方式:

def function(file):
    with open('file.txt', 'r') as f:
        contents = f.readlines()
    lines = []
    for line in f:
        lines.append(line)
    print(contents)    
Run Code Online (Sandbox Code Playgroud)

python function python-3.x

14
推荐指数
1
解决办法
3万
查看次数

"OSError:[Errno 22]无效参数"读取()大文件时

我正在尝试编写一个打印文件校验和的小脚本(使用https://gist.github.com/Zireael-N/ed36997fd1a967d78cb2中的一些代码):

import sys
import os
import hashlib

file = '/Users/Me/Downloads/2017-11-29-raspbian-stretch.img'

with open(file, 'rb') as f:
    contents = f.read()
    print('SHA256 of file is %s' % hashlib.sha256(contents).hexdigest())
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误消息:

Traceback (most recent call last):
  File "checksum.py", line 8, in <module>
    contents = f.read()
OSError: [Errno 22] Invalid argument
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我在macOS High Sierra上使用python 3

python macos file-io python-3.x

13
推荐指数
1
解决办法
7836
查看次数

如何使用函数的返回值作为在python中返回元组的条件

我一直在寻找这样的东西,但我找不到它.

一些背景

我使用opencv从视频文件中检索帧.通常人们会在无限循环中这样做:

while (True):
    s, img = cv.read()
Run Code Online (Sandbox Code Playgroud)

要么

for i in xrange(10000): #just a big number
    s, img = cv.read()
Run Code Online (Sandbox Code Playgroud)

现在我想要检索所有帧并在没有更多帧时退出循环.但是我在python中的技能不够强,无法做我想做的事情.

我想知道什么

read函数(或方法,我不知道它们是如何在python中调用的)返回一个元组:第一个表示操作成功,第二个表示返回的帧.我想在元组的第一个元素为false时打破while循环.有C背景,我想也许这会起作用:

while ((success, img = capture.read())[0]):
    #do sth with img
Run Code Online (Sandbox Code Playgroud)

我认为这会在成功失败时打破循环.但事实并非如此.然后我想也许这会奏效:

while ((success, img = capture.read()).success):
    #do sth with img
Run Code Online (Sandbox Code Playgroud)

它也没用.我不想做类似的事情

while(True):
    s, i = capture.read()
    if (s == False):
        break
Run Code Online (Sandbox Code Playgroud)

如何测试条件while,而不是if成功中断?

python conditional opencv while-loop python-2.7

12
推荐指数
3
解决办法
2167
查看次数

我如何暗示类型与打字相当

假设我想写一个比较排序函数,我可以提示输入必须是一个序列 with Sequence[T](或MutableSequence[T]在这种情况下)。

from typing import MutableSequence, T

def comparison_sort(s: MutableSequence[T]) -> None:
    pass
Run Code Online (Sandbox Code Playgroud)

然而,似乎没有一种开箱即用的方式来暗示T必须具有可比性。(似乎没有ComparableOrdered任何东西typing。)我怎样才能做到这一点?我想避免指定一组特定的类型,例如int, float, 'str` 以便用户也可以暗示他们自己的类型是可比较的。

python python-3.x

12
推荐指数
2
解决办法
3305
查看次数