我bar()在另一个函数中嵌套了一个函数定义foo().现在我试图foo()从嵌套函数访问位于外部函数中的变量bar().但是,由于范围规则,这不起作用(请参阅下面的错误追溯).
我正在寻找类似于global关键字的东西,但这只能让我访问全局变量,而这是某种半全局变量.
这是示例代码:
def foo():
i = 0
def bar():
# how can I get access to the variable from enclosing scope?
i += 1
bar()
foo()
Run Code Online (Sandbox Code Playgroud)
输出是:
$ python test.py
Traceback (most recent call last):
File "test.py", line 7, in <module>
foo()
File "test.py", line 5, in foo
bar()
File "test.py", line 4, in bar
i += 1
UnboundLocalError: local variable 'i' referenced before assignment
Run Code Online (Sandbox Code Playgroud) 我有一个字符串列表,每个字符串代表书籍和他们的一些属性,例如
# each book followed by the price and the name of the genre
book_names = ['love 3 romance',
'rose 6 drama',
'flower 7 nice_story']
Run Code Online (Sandbox Code Playgroud)
我想以某种方式为每本书创建一个新对象,并使其字符串描述属性的其他部分.
这是我尝试过的(显然,它不起作用):
class Book_Class():
price=0
genre=''
book_content=[]
for i in book_names:
name=i.split()[0]
name=Book_Class()
name.price=i.split()[1]
name.genre=i.split()[2]
Run Code Online (Sandbox Code Playgroud)
也许有一种简单的方法来实现我所追求的目标(请告诉我,因为我对编程很新...).
对于原始类型,我可以使用if in:boolean check.但是如果我使用in语法来检查类成员的存在,我会得到一个NameError异常.有没有办法在Python中检查没有异常?或者是尝试除了块之外的唯一方法吗?
这是我的示例代码.
class myclass:
i = 0
def __init__(self, num):
self.i = num
mylist = [1,2,3]
if 7 in mylist:
print "found it"
else:
print "7 not present" #prints 7 not present
x = myclass(3)
print x.i #prints 3
#below line NameError: name 'counter' is not defined
if counter in x:
print "counter in x"
else:
print "No counter in x"
Run Code Online (Sandbox Code Playgroud) 我试图从"糟糕的"中挑选出"好数字".我的问题是我从文本文件中获得的一些数字包含空格(" ").这些函数通过拆分空格来识别它们,这样包含空格的所有行都显示为坏数字,无论它们是好还是坏.
任何人都知道如何解决它们?我现在正在使用它.
def showGoodNumbers():
print ("all good numbers:")
textfile = open("textfile.txt", "r")
for line in textfile.readlines():
split_line = line.split(' ')
if len(split_line) == 1:
print(split_line) # this will print as a tuple
textfile.close
def showBadNumbers():
print ("all bad numbers:")
textfile = open("textfile.txt", "r")
for line in textfile.readlines():
split_line = line.split(' ')
if len(split_line) > 1:
print(split_line) # this will print as a tuple
textfile.close
Run Code Online (Sandbox Code Playgroud)
文本文件如下所示(带注释的所有条目都是"坏"):
13513 51235235235-235232352352-23 - 无效235235 - 太短324-134 314123452566246 …假设我有3种维生素含有C-维生素和D-维生素
ls = [[100,50],[100,49],[100,64]]
Run Code Online (Sandbox Code Playgroud)
巧合的是,这些维生素都具有相同数量的C-维生素.因此,我想对第二种情况(D-维生素)进行排序.我怎么做到这一点?我做了一些研究,发现这是一个例子:
mylist = sorted(mylist, key=itemgetter('name', 'age'))
Run Code Online (Sandbox Code Playgroud)
但是我不明白它的工作原理或原因.我已经使用带有helpmethods的类和这一行完成了关于一个条件的列表排序:
ls.sort(key=Vitamin.get_cVitamin, reverse=True)
Run Code Online (Sandbox Code Playgroud)
我最好想要建立那个......
我正在做家庭作业,以计算用户选择的第n个素数.我有这个工作得很好,并且相当快,但我决定添加一个错误消息,如果用户输入任何大于50000.由于某种原因,这决定不工作,所以我把它拿出来.之后,一旦用户输入他们想要的素数,我的程序就会冻结.
#include <stdio.h>
int main(void)
{
long int pFactor,test,nthCount,target,result,notPrime;
test=2;
nthCount=0;
printf("Which prime number do you want to know?");
scanf("%li",&target);
while (nthCount<target)
{
for(pFactor=test/2;pFactor>1;pFactor--)
{
notPrime=0;
result=(test%pFactor);
if(result==0)
{
notPrime=1;
break;
}
if(notPrime!=1)
{
nthCount++;
notPrime=0;
test++;
}
}
}
test--;
printf("The %li prime number is %li.\n",target,test);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我认为这是与scanf相关的东西,因为我试图打印之后的任何东西都没有出来.
我导入了 matplotlib.pyplot 和 NumPy
我想将桌面上的图像显示到绘图中,但我得到了一个TypeError.
代码 :
img = (image) ( here do we need to give the location of the file or the file directly)
imshow(img, extent=[-25,25,-25,25], cmap = cm.bone)
colorbar()
Error: TypeError: Image data can not convert to float
Run Code Online (Sandbox Code Playgroud)
我使用 Pycharm 作为我的 ide。
我有以下已排序的元组列表,在python中使用"sorted":
L = [("1","blaabal"),
("1.2","bbalab"),
("10","ejej"),
("11.1","aaua"),
("12.1","ehjej"),
("12.2 (c)", "ekeke"),
("12.2 (d)", "qwerty"),
("2.1","baala"),
("3","yuio"),
("4","poku"),
("5.2","qsdfg")]
Run Code Online (Sandbox Code Playgroud)
我的问题是你可以注意到,起初它很好,虽然在"12.2(d)"之后列表重启"2.1",我不知道如何解决这个问题.
谢谢
我想创建两个样本,第一个 y 样本的值在 10^3 到 10^10 的范围内,另一个 x 样本的值在 10^-5 到 10^10 的范围内用于对数图。我尝试了以下方法:
y = np.linspace(1e3,1e10, num = 1000)
x = np.linspace(1e-5,1e10, num = 1000)
Run Code Online (Sandbox Code Playgroud)
但它返回给我一个非均匀分布的样本,只有 1 个 10^-5 数量级的值和更多的 10^9 数量级的 x,以及 10^-5 和 10^7 之间的零值。这就是我得到的 x:
[1.00000000e-05 1.00100100e+07 2.00200200e+07 3.00300300e+07
4.00400400e+07 5.00500501e+07 6.00600601e+07 7.00700701e+07
8.00800801e+07 9.00900901e+07 1.00100100e+08 1.10110110e+08
1.20120120e+08 1.30130130e+08 1.40140140e+08 1.50150150e+08
...
Run Code Online (Sandbox Code Playgroud)
我想要一个值均匀分隔的样本:每个 10^ 订单具有相同数量的值,因为我需要它来绘制对数图。为什么 linspace 不起作用,我该如何解决?
对于n站点,给出n*n矩阵A,其A[i][j]表示从站i到j(i,j <= n)的直接旅程的时间.
在车站之间旅行的人总是寻求最少的时间.给定两个站号a,b如何计算它们之间的最短旅行时间?
没有使用图论可以解决这个问题,即仅仅通过矩阵A?
我正在处理这个名为timeKeeper.h(和.c)的大型项目中的文件
--------------编辑---------------修复了那些仍然被破坏的人------------- -
#ifndef TIMEKEEPER_H_
#define TIMEKEEPER_H_
#include <time.h>
#include <stdbool.h>
bool isAfter(time_t time);
void setTime(char seconds, char minutes, char hours, char day,
char month, char year);
void tickSeconds(void);
time_t getCurrentTime(void);
time_t createTime(char seconds, char minutes, char hours, char day,
char month, char year);
void startTime(void);
time_t addSeconds(int seconds, time_t time);
long timeRemaining(time_t time);
void rtc_set(char seconds, char minutes, char hours, char days, char months,
char year);
#endif
Run Code Online (Sandbox Code Playgroud)
当我尝试构建我的项目时,此文件中有一堆错误(以及任何使用time.h的文件).以下是timeKeeper.h中的一些错误:
expected ')' before 'time' Line 6
expected '"', ',', ';','asm', or …Run Code Online (Sandbox Code Playgroud)