我最近开始学习 Python,我不明白为什么 Python 会这样:
>>> “好的”
'好的'
>>> """好的"""
'好的'
>>>“不好”
文件“<stdin>”,第 1 行
“不好'
^
语法错误:扫描字符串文字时 EOL
>>> "不行"""
'不好'
由于引号的数量不匹配,为什么最后一条语句不会出错?
考虑从包派生的这个数据类pydantic:
from typing import List
from pydantic import BaseModel
class Bucket(BaseModel):
setting: List[str]
fight_1: List[int]
cause_1: List[str]
Run Code Online (Sandbox Code Playgroud)
让my_bucket成为 的一个实例Bucket:
my_bucket = Bucket(setting=['some_value'], fight_1=[0], cause_1=['other_value'])
Run Code Online (Sandbox Code Playgroud)
基本上我希望能够做到
my_bucket['setting']
Run Code Online (Sandbox Code Playgroud)
然后返回['some_value'],但我得到:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-18-cacbdc1698e9> in <module>
----> 1 my_bucket['setting']
TypeError: 'Bucket' object is not subscriptable
Run Code Online (Sandbox Code Playgroud) 我正在开发一个基于 django 的 web 应用程序,它以 python 文件作为输入,其中包含一些函数,然后在后端我有一些列表作为参数通过用户函数传递,这将生成一个单值输出。生成的结果将是用于一些进一步的计算。
以下是用户文件中的函数的样子:
def somefunctionname(list):
''' some computation performed on list'''
return float value
Run Code Online (Sandbox Code Playgroud)
目前我使用的方法是将用户的文件作为普通文件输入。然后在我的 views.py 中,我将文件作为模块执行并使用 eval 函数传递参数。下面给出了片段。
这里 modulename 是我从用户那里获取并作为模块导入的 python 文件名
exec("import "+modulename)
result = eval(f"{modulename}.{somefunctionname}(arguments)")
Run Code Online (Sandbox Code Playgroud)
哪个工作得很好。但我知道这不是安全的方法。
我的问题,有没有其他方法可以安全地运行用户文件,因为我使用的方法不安全?我知道提议的解决方案不能完全证明,但是我可以运行它的其他方式是什么(例如,如果它可以通过 dockerization 解决,那么我可以使用 API 的方法或一些外部工具是什么)?或者如果可能的话,有人可以告诉我如何简单地沙盒这个或任何可以帮助我的教程..?
任何参考或资源都会有所帮助。
我正在尝试制作一个以可执行文件名作为参数的程序,运行可执行文件并报告该运行的输入和输出。例如,考虑一个名为“circle”的子程序。我的程序需要运行以下内容:
$ python3 capture_io.py ./circle
输入圆的半径:10
地区:314.158997
[('output', '输入圆的半径:'), ('input', '10\n'), ('output', 'Area: 314.158997\n')]
我决定使用pexpect模块来完成这项工作。它有一个方法interact可以让用户与子程序进行交互,如上所示。它还需要 2 个可选参数:output_filter和input_filter. 从文档:
该
output_filter会通过了所有从子进程的输出。该input_filter会从用户通过了所有的键盘输入。
所以这是我写的代码:
import sys
import pexpect
_stdios = []
def read(data):
_stdios.append(("output", data.decode("utf8")))
return data
def write(data):
_stdios.append(("input", data.decode("utf8")))
return data
def capture_io(argv):
_stdios.clear()
child = pexpect.spawn(argv)
child.interact(input_filter=write, output_filter=read)
child.wait()
return _stdios
if __name__ == '__main__':
stdios_of_child = capture_io(sys.argv[1:])
print(stdios_of_child)
Run Code Online (Sandbox Code Playgroud)
$ python3 capture_io.py ./circle Enter radius of circle: …
我遇到过这样的代码:
from random import randint
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
points = [Point(randint(1, 10), randint(1, 10)) for _ in range(10)]
xs = [point.x for point in points]
ys = [point.y for point in points]
Run Code Online (Sandbox Code Playgroud)
而且我认为这段代码不是Pythonic,因为它会重复。如果将另一个维度添加到Point类中,则需要编写一个全新的循环,如下所示:
zs = [point.z for point in points]
Run Code Online (Sandbox Code Playgroud)
所以我试图通过写这样的东西来使它更像 Pythonic:
xs, ys = zip(*[(point.x, point.y) for point in p])
Run Code Online (Sandbox Code Playgroud)
如果添加了新的维度,没问题:
xs, ys, zs = zip(*[(point.x, point.y, point.z) for point in p])
Run Code Online (Sandbox Code Playgroud)
但是当有数百万个点时,这几乎比其他解决方案慢10 倍,尽管它只有一个循环。我认为这是因为 …
我在列表中有多个字典。我想用自定义键对字典进行排序。就我而言,我想使用Date键对其进行排序。我的意思是将Date钥匙移到第一个位置。使用Date键对字典进行排序的有效方法是什么?
PS:我不想按Date.
[
{
"AmazonS3":6.54,
"AmazonEC2":27.55,
"AmazonCloudWatch":0.51,
"Date":"2020-07-01"
},
{
"AmazonEC2":27.8,
"Date":"2020-07-02"
},
{
"AmazonElastiCache":0.01,
"AmazonEC2":35.34,
"Date":"2020-07-03"
}
]
Run Code Online (Sandbox Code Playgroud)
预期输出:
...
{
"Date":"2020-07-03",
"AmazonElastiCache":0.01,
"AmazonEC2":35.34
}
...
Run Code Online (Sandbox Code Playgroud) 我一直在研究如何创建自己的装饰器,并给出了以下示例:
def counter(func):
def wrapper(*args, **kwargs):
wrapper.count += 1
# Call the function being decorated and return the result
return wrapper.count
wrapper.count = 0
# Return the new decorated function
return wrapper
# Decorate foo() with the counter() decorator
@counter
def foo():
print('calling foo()')
foo()
foo()
print('foo() was called {} times.'.format(foo.count))
Run Code Online (Sandbox Code Playgroud)
我不明白那段代码的逻辑。
wrapper.count)?我需要一个字典,它会自动填充每个缺失的访问键的默认值。我已经找到了defaultdict一些其他方法来实现此目的,但我的情况的问题是我希望每个键的默认值特定于键本身。
例如,defaultdict我可以实现这样的目标:
from collections import defaultdict
d = defaultdict(lambda: 5)
> d[1] = 3
> d[1]
> 3
> d[2]
> 5
Run Code Online (Sandbox Code Playgroud)
但是,如果我需要每个访问的缺失键的默认值,该怎么办key + 5?就像是:
from collections import defaultdict
d = defaultdict(lambda key: key + 5) # <-- This does not work as defaultdict expects lambda function to be without any parameters
> d[1] = 3
> d[1]
> 3
> d[2]
> 7 <- Calculated from accessed key + 5 (2+5)
> d[5] …Run Code Online (Sandbox Code Playgroud) 我这里有 2 个列表:
list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]
Run Code Online (Sandbox Code Playgroud)
我想让数字分配给情绪?(happy 等于 2,sad 等于 5,以此类推)。理想情况下,我想这样做,以便您可以比较 list1 中的项目,例如:
if happy > sad:
print ("you are happy")
Run Code Online (Sandbox Code Playgroud)
我想让这段代码尽可能高效,所以我不想分别为 list1 中的每个变量分配一个数字。
我正在使用 Windows 10 和 Pycharm IDE。有.isascii()没有在 google colab 上不起作用的原因?当我在 google colab 上尝试代码片段时,我得到:
AttributeError: 'str' object has no attribute 'isascii'
Run Code Online (Sandbox Code Playgroud)
如果我在我的 IDE 上尝试相同的代码,我会得到True.
thisstr = "Hoho"
k = thisstr.isascii()
print(k)
Run Code Online (Sandbox Code Playgroud) python-3.x ×10
python ×8
dictionary ×2
defaultdict ×1
django ×1
docker ×1
fork ×1
list ×1
optimization ×1
pexpect ×1
pty ×1
pydantic ×1
quotes ×1
string ×1
wrapper ×1