为简单起见,这是我想要做的精简版:
def foo(a):
# I want to print the value of the variable
# the name of which is contained in a
Run Code Online (Sandbox Code Playgroud)
我知道如何在PHP中执行此操作:
function foo($a) {
echo $$a;
}
global $string = "blah"; // might not need to be global but that's irrelevant
foo("string"); // prints "blah"
Run Code Online (Sandbox Code Playgroud)
有什么办法吗?
我编写了一个程序来解决y = a^x
,然后将其投影到图表上.问题是每当a < 1
我收到错误时:
ValueError:具有基数10的int()的无效文字.
有什么建议?
这是追溯:
Traceback (most recent call last):
File "C:\Users\kasutaja\Desktop\EksponentfunktsioonTEST - koopia.py", line 13, in <module>
if int(a) < 0:
ValueError: invalid literal for int() with base 10: '0.3'
Run Code Online (Sandbox Code Playgroud)
每次我放一个小于1但大于0的数字时就会出现问题.对于这个例子,它是0.3.
这是我的代码:
# y = a^x
import time
import math
import sys
import os
import subprocess
import matplotlib.pyplot as plt
print ("y = a^x")
print ("")
a = input ("Enter 'a' ")
print ("")
if int(a) < 0:
print ("'a' is negative, …
Run Code Online (Sandbox Code Playgroud) 我正在寻找有人解释如何使用的基本知识,而不是使用setattr()
.
我的问题出现了尝试使用一个类方法/函数来返回数据然后放入另一个方法/函数.在这种情况下,也许更简单的方法会好得多,但我试图理解类的工作原理.这个问题似乎取决于此问题setattr()
,这是我试图对此进行相当简单的使用.
虽然它是不太一样的问题,我在下面的Python困难的方法,ex42 -the while
环@线18-41.
我尝试编写一个\__init__()
,然后用它getattr()
来思考可能需要在类的命名空间中的东西,但这似乎没有帮助.
#! /bin/python2.6
class HolyGrail(object):
def __init__(self):
self.start = 'start_at_init'
# function definition in question:
# TypeError: 'str' object is not callable
def run_it(self):
start = setattr(self, 'name', 'get_thing')
start = self.name
# Something wrong here?
value_returned = start() #I believe this == self.get_thing()
use_it(value_returned)
"""
# alternate function definitions
# NameError: global name 'start' is not defined
def __init__(self):
self.start = 'get_thing'
def run_it(self): …
Run Code Online (Sandbox Code Playgroud) 我如何(轻松地)获取一个字符串,例如"sin(x)*x^2"
用户可能在运行时输入的字符串,并生成一个可以评估任何值的Python函数x
?
我想将一个数学运算符和要比较的数值传递给一个函数.这是我破碎的代码:
def get_truth(inp,relate,cut):
if inp print(relate) cut:
return True
else:
return False
Run Code Online (Sandbox Code Playgroud)
并称之为
get_truth(1.0,'>',0.0)
Run Code Online (Sandbox Code Playgroud)
哪个应该返回True.
我正在尝试创建一个函数来绘制我告诉它的任何公式.
import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
x = np.array(x_range)
y = formula
plt.plot(x, y)
plt.show()
Run Code Online (Sandbox Code Playgroud)
当我尝试调用它时会发生以下错误,我相信它会在它到达之前尝试进行乘法运算y = formula
.
graph(x**3+2*x-4, range(-10, 11))
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
graph(x**3+2*x-4, range(-10, 11))
NameError: name 'x' is not defined
Run Code Online (Sandbox Code Playgroud) 假设我有列表得分= [1,2,3,4,5],并且在我的程序运行时它会被更改.如何将其保存到文件中以便下次运行程序时我可以将更改后的列表作为列表类型进行访问?
我试过了:
score=[1,2,3,4,5]
with open("file.txt", 'w') as f:
for s in score:
f.write(str(s) + '\n')
with open("file.txt", 'r') as f:
score = [line.rstrip('\n') for line in f]
print(score)
Run Code Online (Sandbox Code Playgroud)
但这会导致列表中的元素不是整数.
在我的代码中,我eval
用来评估用户给出的字符串表达式.有没有办法编译或以其他方式加快这种说法?
import math
import random
result_count = 100000
expression = "math.sin(v['x']) * v['y']"
variable = dict()
variable['x'] = [random.random() for _ in xrange(result_count)]
variable['y'] = [random.random() for _ in xrange(result_count)]
# optimize anything below this line
result = [0] * result_count
print 'Evaluating %d instances of the given expression:' % result_count
print expression
v = dict()
for index in xrange(result_count):
for name in variable.keys():
v[name] = variable[name][index]
result[index] = eval(expression) # <-- option ONE
#result[index] = math.sin(v['x']) * …
Run Code Online (Sandbox Code Playgroud) 我试图通过添加基于用户输入列表的Q对象在Django中构建一个复杂的查询:
from django.db.models import Q
q = Q()
expressions = [
{'operator': 'or', 'field': 'f1', 'value': 1},
{'operator': 'or', 'field': 'f2', 'value': 2},
{'operator': 'and', 'field': 'f3', 'value': 3},
{'operator': 'or', 'field': 'f4', 'value': 4},
]
for item in expressions:
if item['operator'] == 'and':
q.add(Q(**{item['field']:item['value']}), Q.AND )
elif item['operator'] == 'or':
q.add(Q(**{item['field']:item['value']}), Q.OR )
Run Code Online (Sandbox Code Playgroud)
基于此,我期望得到以下条件的查询:
f1 = 1 or f2 = 2 and f3 = 3 or f4 = 4
Run Code Online (Sandbox Code Playgroud)
其中,基于默认运算符优先级将执行为
f1 = 1 or (f2 = 2 and f3 …
Run Code Online (Sandbox Code Playgroud)