小编Dha*_*ara的帖子

为什么嵌套函数可以从外部函数访问变量,但不允许修改它们

在下面的第二种情况下,Python试图寻找一个局部变量.当它没有找到一个时,为什么它不能像在第一种情况下那样在外部范围内看?

这在本地范围内查找x,然后在外部范围内查找:

def f1():
    x = 5
    def f2():
         print x
Run Code Online (Sandbox Code Playgroud)

这给出了local variable 'x' referenced before assignment错误:

def f1():
    x = 5
    def f2():
        x+=1
Run Code Online (Sandbox Code Playgroud)

我不允许修改函数f2()的签名,所以我不能传递和返回x的值.但是,我确实需要一种方法来修改x.有没有办法明确告诉Python在外部范围内查找变量名称(类似于global关键字)?

Python版本:2.7

python scope

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

各种numpy随机函数之间的差异

所述numpy.random模块定义了以下4个功能,所有似乎从连续均匀分布返回浮点betweeb [0,1.0).这些功能之间的区别是什么(如果有的话)?

random_sample([size])在半开区间[0.0,1.0]中返回随机浮点数.

random([size])在半开区间[0.0,1.0]中返回随机浮点数.

ranf([size])在半开区间[0.0,1.0]中返回随机浮点数.

sample([size])在半开区间[0.0,1.0]中返回随机浮点数.

---------------------------编辑关注--------------------- ------------------

我在numpy.random源代码中找到了以下支持@askewchan的答案:

# Some aliases:
ranf = random = sample = random_sample
__all__.extend(['ranf','random','sample'])
Run Code Online (Sandbox Code Playgroud)

python numpy

30
推荐指数
1
解决办法
5120
查看次数

为什么Numpy以不同方式处理+ = b和a = a + b

以下numpy行为是故意还是错误?

from numpy import *

a = arange(5)
a = a+2.3
print 'a = ', a
# Output: a = 2.3, 3.3, 4.3, 5.3, 6.3 

a = arange(5)
a += 2.3
print 'a = ', a
# Output: a = 2, 3, 4, 5, 6
Run Code Online (Sandbox Code Playgroud)

Python版本:2.7.2,Numpy版本:1.6.1

python numpy

24
推荐指数
2
解决办法
714
查看次数

使用jQuery切换hide/show <tr>

我将此代码显示<tr>在我的表中,但每次单击时,它都会隐藏单击按钮时必须显示的文本框.

下面是我jQuery显示文本框的代码:

$(function() {
   $('#btnAdd').click(function() {
       $('.td1').show();
   });
});
Run Code Online (Sandbox Code Playgroud)

这是我的代码<table>:

<button id="btnAdd" name="btnAdd" onclick="toggle();" class="span1">ADD</button>
<tr class="td1" id="td1" style="">  
     <td><input type="text" name="val1" id="val1"/></td>
     <td><input type="text" name="val2" id="val2"/></td>
</tr>
Run Code Online (Sandbox Code Playgroud)

html javascript jquery

12
推荐指数
1
解决办法
6万
查看次数

Matplotlib图例字体大小

我在下面的代码中错误地使用了fontsize参数吗?根据文档,这应该是一个有效的关键字参数.

import pylab
pylab.plot(range(5), label='test')
pylab.legend(fontsize='small') 
pylab.show()
Run Code Online (Sandbox Code Playgroud)

追溯:

Traceback (most recent call last):
  File "test_label.py", line 6, in <module>
    pylab.legend(fontsize='small')
  File "C:\swframe\python-V01-01\lib\site-packages\matplotlib\pyplot.py", line 2
791, in legend
    ret =  gca().legend(*args, **kwargs)
  File "C:\swframe\python-V01-01\lib\site-packages\matplotlib\axes.py", line 447
5, in legend
    self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'fontsize'
Run Code Online (Sandbox Code Playgroud)

Python:2.7,Matplotlib:1.1.0

编辑:注意,我不是在寻找其他方法来设置字体大小.我想知道为什么会出错.

python matplotlib

5
推荐指数
1
解决办法
4060
查看次数

如何将数据从XML文件存储到android中的SQLite数据库

我正在开发一个应用程序 - 当用户成功登录时,将从URL获取XML文件,并在列表视图中显示XML数据.

如何在SQLite数据库中存储该数据,以便脱机用户可以看到存储在数据库中的数据?我还想创建一个刷新按钮,它会显示一个更新的XML文件,并在单击时将其存储在SQLite中.

xml database sqlite url android

4
推荐指数
1
解决办法
5171
查看次数

如何在Swift iOS 8中使用requestAccessToEntityType方法

我试图通过EKEventStore在iOS8中使用Swift 来获取事件列表,据我所知,文档尚未更新.

这就是我想要做的:

let eventStore =  EKEventStore()

eventStore.requestAccessToEntityType(EKEntityType(), EKEventStoreRequestAccessCompletionHandler(Bool(), NSError(){}))
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

'EKEventStoreRequestAccessCompletionHandler' is not constructible with '(Bool, NSError)

你知道如何在Swift中正确使用方法或处理程序吗?

eventkit ekeventstore swift ios8

4
推荐指数
1
解决办法
2716
查看次数

Zipfile模块错误:文件不是zip文件

我有这个代码:

# File: zipfile-example-1.py

import zipfile,os,glob

file = zipfile.ZipFile("Apap.zip", "w")

# list filenames
for name in glob.glob("C:\Users/*"):
    print name
    file.write(name,os.path.basename(name),zipfile.ZIP_DEFLATED)
file = zipfile.ZipFile("Apap.zip", "r")
for info in file.infolist():
    print info.filename, info.date_time, info.file_size, info.compress_size
Run Code Online (Sandbox Code Playgroud)

产生此错误:

raceback (most recent call last):
  File "C:/Users/Desktop/zip.py", line 11, in <module>
    file = zipfile.ZipFile("Apap.zip", "r")
  File "C:\Python27\lib\zipfile.py", line 712, in __init__
    self._GetContents()
  File "C:\Python27\lib\zipfile.py", line 746, in _GetContents
    self._RealGetContents()
  File "C:\Python27\lib\zipfile.py", line 761, in _RealGetContents
    raise BadZipfile, "File is not a zip file"
BadZipfile: File is …
Run Code Online (Sandbox Code Playgroud)

python

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

检查集合是否仅包含其他集合中的元素的最佳方法是什么?

检查数组/元组/列表是否只包含另一个数组/元组/列表中的元素的最佳方法是什么?

我尝试了以下两种方法,对于不同类型的集合,它们更好/更pythonic?我可以使用哪些其他(更好)方法进行此项检查?

import numpy as np

input = np.array([0, 1, -1, 0, 1, 0, 0, 1])
bits = np.array([0, 1, -1])

# Using numpy
a=np.concatenate([np.where(input==bit)[0] for bit in bits])
if len(a)==len(input):
    print 'Valid input'

# Using sets
if not set(input)-set(bits):
    print 'Valid input'
Run Code Online (Sandbox Code Playgroud)

python

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

属性的教条

如何访问属性的文档字符串而不是它所拥有的值?

为什么以下代码中的2个帮助函数会返回不同的文档字符串abc.x

class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        print "** In get **"
        return self._x

    x = property(getx, doc="I'm the 'x' property.")

abc = C()
help(abc) # prints the docstring specified for property 'x'
help(abc.x) # prints the docstring for "None", the value of the property
Run Code Online (Sandbox Code Playgroud)

python python-2.7

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

在matplotlib中注释尺寸

我想在matplotlib图中注释某些长度.例如,A点和B点之间的距离.

为此,我想我可以使用注释并弄清楚如何提供箭头的开始和结束位置.或者,使用箭头并标记点.

我试图使用后者,但我无法弄清楚如何得到一个双头箭头:

from pylab import *

for i in [0, 1]:
    for j in [0, 1]:
        plot(i, j, 'rx')

axis([-1, 2, -1, 2]) 
arrow(0.1, 0, 0, 1, length_includes_head=True, head_width=.03) # Draws a 1-headed arrow
show()
Run Code Online (Sandbox Code Playgroud)

如何制作双头箭头?更好的是,还有另一种(更简单的)matplotlib数字标记尺寸的方法吗?

python matplotlib

2
推荐指数
1
解决办法
2061
查看次数

使用 JENA api 读取文件时出错

对于以下代码:

Model m2=ModelFactory.createDefaultModel();
m2.read("Untitled.xml");
Run Code Online (Sandbox Code Playgroud)

我收到错误: Exception in thread "main" com.hp.hpl.jena.shared.JenaException: java.net.MalformedURLException: no protocol: Untitled.xml

有人可以帮我吗?

java jena

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

为什么会出现内存错误?

这是我的代码:

i=int(input("enter your number"))
j=int(input("enter your number"))
if i>j: #making x always greater than y
    x=i
    y=j
elif i<j:
    x=j
    y=i
else:
    print("invalid")
k=y
cyclelength=[]
while k<=x:
    list=[k]
    while k!=1:
        if(k%2==0):
            k=i//2
        else:
            k=3*k+1
        list.append(k)
    cyclelength.append(len(list))
    k+=1
print(y," ",x," ",max(cyclelength))
Run Code Online (Sandbox Code Playgroud)

我得到以下异常:

Traceback (most recent call last):
  File "C:/Python32/uva100.py", line 21, in <module>
    list.append(k)
MemoryError
Run Code Online (Sandbox Code Playgroud)

python

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