sample = {('red', 'blue', 'purple') : 'color', 'redo' : 'again', 'bred' : 'idk', 'greeting' : ('hi', 'hello')}
def search(c):
if c in sample.keys():
return sample[c]
print(search('red'))
Run Code Online (Sandbox Code Playgroud)
这返回None. 我知道我可以将它们分开并制作具有相同值的多个键,但如果可以的话,我真的很想避免这样做。我可以吗?
而且我还希望能够搜索值(也可能是元组)并获得相应的键。
我试图找到计算这个双for循环的每次迭代的公式(例如在 python 中):
for i in range(5):
for j in range(5):
count = MYSTERIOUS_FORMULA
print count
Run Code Online (Sandbox Code Playgroud)
这里 count 的最终值应该是 25。
我试过,count=(i+1)*j但它产生0,1,2,3,4,0,2,4等。
我正在fields使用元类设置类属性:
class MyMeta(type):
def __new__(mcs, name, bases, clsdict):
clsdict['fields'] = {k: v
for k, v in clsdict.items()
if <my_condition>}
return super(MyMeta, mcs).__new__(mcs, name, bases, clsdict)
class MyBaseClass(metaclass=MyMeta):
fields = {}
Run Code Online (Sandbox Code Playgroud)
以下实例化导致预期结果:
class SubClass(MyBaseClass):
param1 = 1 # meets <my_condition>
>>> SubClass.fields
{param1: 1}
Run Code Online (Sandbox Code Playgroud)
但如果我现在子类SubClass,fields是空的:
class SubSubClass(SubClass):
pass
>>> SubSubClass.fields
{}
Run Code Online (Sandbox Code Playgroud)
我如何能够更新继承层次结构中所有类的 classdict 以便fields从基类更新变量?
我想从数组中获取两个最小值x。但是当我使用时np.where:
A,B = np.where(x == x.min())[0:1]
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
ValueError:需要多个值才能解压
如何解决此错误?我是否需要在数组中按升序排列数字?
我有一个小项目,所以一周前我开始在 Python 上做一些测试。我必须显示 RGB 图像的 3 个通道,但pyplot.imshow()函数显示以下内容:

我想显示红色、绿色和蓝色通道,如下所示:

到目前为止,这是我的代码:
from matplotlib import pyplot as plt
from PIL import Image
import numpy as np
img1 = np.array(Image.open('img1.png'))
figure, plots = plt.subplots(ncols=3, nrows=1)
for i, subplot in zip(range(3), plots):
temp = np.zeros(img1.shape, dtype='uint8')
temp = img1[:,:,i]
subplot.imshow(temp)
subplot.set_axis_off()
plt.show()
Run Code Online (Sandbox Code Playgroud)
我不在任何笔记本上工作。相反,我在 PyCharm 中工作。我读了这篇文章:24739769。我查了一下,img1.dtype是的uint8,所以我不知道如何展示我想要的东西。
我已经读过这个很酷的新词典类型,即transformdict
我想在我的项目中使用它,通过使用常规dict初始化一个新的转换字典:
tran_d = TransformDict(str.lower, {'A':1, 'B':2})
Run Code Online (Sandbox Code Playgroud)
哪个成功但是当我运行时:
tran_d.keys()
Run Code Online (Sandbox Code Playgroud)
我明白了:
['A', 'B']
Run Code Online (Sandbox Code Playgroud)
在创建新的转换字典时,您如何建议在参数(常规)字典上执行转换函数?为了清楚起见,我想要以下内容:
tran_d.keys() == ['a', 'b']
Run Code Online (Sandbox Code Playgroud) 演示我所要求的内容的几行代码是:
>>> x = ()
>>> for i in range(1000000):
... x = (x,)
>>> x.__hash__()
=============================== RESTART: Shell ===============================
Run Code Online (Sandbox Code Playgroud)
1000000 可能过多,但它表明在散列嵌套元组(并且我假设其他对象)时存在某种形式的限制。只是为了澄清,我没有重新启动 shell,当我尝试哈希时它会自动执行此操作。
我想知道这个限制是什么,为什么会发生(以及为什么它没有引发错误),以及是否有解决方法(以便我可以将这样的元组放入集合或字典中)。
我想制作一个单词频率分布,x轴上的字和y轴上的频率计数.
我有以下列表:
example_list = [('dhr', 17838), ('mw', 13675), ('wel', 5499), ('goed', 5080),
('contact', 4506), ('medicatie', 3797), ('uur', 3792),
('gaan', 3473), ('kwam', 3463), ('kamer', 3447),
('mee', 3278), ('gesprek', 2978)]
Run Code Online (Sandbox Code Playgroud)
我试着先把它转换成一个pandas DataFrame,然后使用pd.hist()下面的例子中的as,但我只是想不出来,并认为它实际上是直接的,但可能我错过了一些东西.
import numpy as np
import matplotlib.pyplot as plt
word = []
frequency = []
for i in range(len(example_list)):
word.append(example_list[i][0])
frequency.append(example_list[i][1])
plt.bar(word, frequency, color='r')
plt.show()
Run Code Online (Sandbox Code Playgroud) 在字符串中格式化dict键的正确方法是什么?
当我这样做:
>>> foo = {'one key': 'one value', 'second key': 'second value'}
>>> "In the middle of a string: {foo.keys()}".format(**locals())
Run Code Online (Sandbox Code Playgroud)
我期待的是:
"In the middle of a string: ['one key', 'second key']"
Run Code Online (Sandbox Code Playgroud)
我得到了什么:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
"In the middle of a string: {foo.keys()}".format(**locals())
AttributeError: 'dict' object has no attribute 'keys()'
Run Code Online (Sandbox Code Playgroud)
但正如你所看到的,我的dict有键:
>>> foo.keys()
['second key', 'one key']
Run Code Online (Sandbox Code Playgroud) 假设我有一个模块,并且我想弃用该模块中的某些内容。这对于函数来说非常简单,本质上这可以使用装饰器来完成:
import warnings
def deprecated(func):
def old(*args, **kwargs):
warnings.warn("That has been deprecated, use the new features!", DeprecationWarning)
return func(*args, **kwargs)
return old
@deprecated
def func():
return 10
func()
Run Code Online (Sandbox Code Playgroud)
DeprecationWarning:该功能已被弃用,请使用新功能!
10
但是,如果我想弃用一个不重要的常量,则无法将装饰器应用于变量。我正在玩弄,似乎可以对模块进行子类化并用于__getattribute__发出警告:
我这里使用NumPy只是为了说明原理:
import numpy as np
class MyMod(type(np)): # I could also subclass "types.ModuleType" instead ...
def __getattribute__(self, name):
if name in {'float', 'int', 'bool', 'complex'}:
warnings.warn("that's deprecated!", DeprecationWarning)
return object.__getattribute__(self, name)
np.__class__ = MyMod
np.float
Run Code Online (Sandbox Code Playgroud)
弃用警告:已弃用!
漂浮
然而,这似乎不可能从包内完成(至少在顶层),因为我无法访问自己的模块。我必须创建另一个包来对主包进行猴子修补。
有没有更好的方法来“弃用”从包中访问变量,而不是子类化“模块”类和/或使用对另一个包的顶级模块进行猴子修补的元包?
python ×10
dictionary ×3
python-3.x ×3
matplotlib ×2
numpy ×2
algorithm ×1
arrays ×1
distribution ×1
frequency ×1
hash ×1
image ×1
inheritance ×1
metaclass ×1
methods ×1
module ×1
nested-loops ×1
plot ×1
rgb ×1