我还是Python的初学者,我想知道为什么:
dict = {}
dict[0] = '123'
a = 0
if dict["{}".format(a)]["{}".format(a)] == '1':
print('True')
Run Code Online (Sandbox Code Playgroud)
给我一个关键错误'0'但不是这个:
dict = {}
dict[0] = '123'
if dict[0][0] == '1':
print('True')
Run Code Online (Sandbox Code Playgroud)
提前致谢.
我正在从word2vec C代码生成的二进制文件中加载经过预训练的向量,如下所示:
model_1 = Word2Vec.load_word2vec_format('vectors.bin', binary=True)
Run Code Online (Sandbox Code Playgroud)
我正在使用这些向量生成句子的向量表示,这些句子包含的单词可能在中不存在向量vectors.bin。例如,如果vectors.bin单词“酸奶”没有关联的向量,我会尝试
yogurt_vector = model_1['yogurt']
Run Code Online (Sandbox Code Playgroud)
我明白了KeyError: 'yogurt',这很有意义。我想要的是能够接受没有相应向量的句子单词,并为其添加表示形式model_1。从这篇文章中我知道,您不能继续训练C向量。那么有没有办法为model_2没有向量的单词训练新模型并model_2与之合并model_1呢?
或者,是否有一种方法可以在我实际尝试检索该模型之前测试该模型是否包含单词,以便至少可以避免KeyError?
我可能做了一些愚蠢的事情,但无法弄清楚是什么,它让我疯了,因为它是微不足道的,我有其他应用程序使用相同的逻辑.
所以我有一个模型客户和模型说明.每个客户我都可以创建很多Notes.在Notes中,Customer定义为外键.
view.py
@login_required
def note_new(request,pk):
contact = get_object_or_404(Contacts, pk=pk)
if request.method == "POST":
form = NoteForm(request.POST)
if form.is_valid():
note = form.save(commit=False)
note.pub_date = timezone.now()
note.save()
return redirect('contact_details',pk=contact.id)
else:
form = NoteForm(pk=contact.id)
return render(request, 'customer/note_edit.html', {'form': form})
Run Code Online (Sandbox Code Playgroud)
forms.py
class NoteForm(forms.ModelForm):
class Meta:
model = Note
fields = [ 'title','body','contact' ]
def __init__(self,*args,**kwargs):
contact_id = kwargs.pop('pk')
# self.fields['contact'].initial = contact_id
super(NoteForm,self).__init__(*args,**kwargs)
self.initial['contact'] = contact_id
self.fields['contact'].widget.attrs['readonly'] = True
Run Code Online (Sandbox Code Playgroud)
所以表格显示确定,点击保存后我就收到了
KeyError at/customer/note/new/9'pk'请求方法:POST请求URL:http://127.0.0.1:8000/customer/note/new/9 Django版本:1.8异常类型:KeyError异常值:
'pk '异常位置:C:\ Users\I812624\dev\mrp\src\customer\forms.py in__init__,第48行Python版本:2.7.1 …
我想创建一个DataFrame的索引子集并在其中使用一个变量.在这种情况下,我想将第一列的所有-9999值更改为NA.如果我这样做:df[df[:1] .== -9999, :1] = NA它的工作原理应该如此..但是如果我使用变量作为索引器它会导致错误(LoadError:KeyError:key:我找不到):
i = 1
df[df[:i] .== -9999, :i] = NA
Run Code Online (Sandbox Code Playgroud) 嗨,我仍然是python的新手,想知道为什么这行:
RP[p][t] = demand[p][t] / fillingrate[p]
Run Code Online (Sandbox Code Playgroud)
导致错误:KeyError:0
它遵循代码的相关部分.这只是一个记号错误或解决它的最佳方法是什么?
productname = ('milk', 'yoghurt', 'buttermilk')
fillingrate = (1.5, 1.0, 2.0)
day = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
demand = [
(5, 4, 3, 3, 4, 9, 13, 5, 4, 4, 3, 5, 10, 12),
(3, 5, 3, 5, 5, 4, 3, 4, 3, 4, 3, 4, 5, 5),
(3, 3, 5, 4, 4, 5, 4, 3, 4, 3, 4, 5, 4, 5)
] …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写康威的生命游戏代码。据我所知,程序应该完成,但是当我运行它时,我得到 KeyError: 0,据我了解,这意味着引用了不存在的字典键。字典 (cell_dict) 包含形成死/活单元格的 20x20 tkinter 按钮网格。
这是完整的代码:
#imports
import tkinter
import random
#functions
def step(): #updates the status of each cell
for i in range(0,20): # runs through each cell to check the number of living neighbors
for j in range(0,20):
cell = cell_dict[i][j] #key error happens here
pop = 0
for n in range(-1,2): #checks each neighbor and tracks the number of alive ones
for m in range(-1,2):
if i+n in range(0,20) and j+m in range(0,20):
if …Run Code Online (Sandbox Code Playgroud) 我正在用 python 制作一个不和谐的音乐机器人,当我在我的电脑上运行该机器人时,一切正常,但是当我通过 Replit.com 运行它时,它会返回一个错误。
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'dislike_count'
Run Code Online (Sandbox Code Playgroud)
我知道这个错误是由 DiscordUtils 文件中的一行引起的dislikes = data['dislike_count'],所以在我的电脑上我可以直接注释掉该行,一切正常。
但在 Replit.com 上似乎无法更改或修改已安装的库文件,那么我应该如何解决这个问题?我也尝试过 Heroku,但这是同样的问题。
我希望有人能帮助我,提前谢谢!
我对 with_columns 中的 Polars LazyFrame“Structs”(pl.struct)和“apply”(又名 map_elements)有以下问题
这里的想法是尝试将自定义逻辑应用于属于多个列的一组值
我已经能够使用 DataFrames 实现这一点;但是,当切换到 LazyFrames 时,每当我尝试访问由结构发送到函数的字典中的列时,就会引发 KeyError。我逐一循环列,以便应用不同的函数(在其他地方映射到它们的名称,但在下面的示例中,为了简单起见,我将仅使用相同的函数)
my_df = pl.DataFrame(
{
"foo": ["a", "b", "c", "d"],
"bar": ["w", "x", "y", "z"],
"notes": ["1", "2", "3", "4"]
}
)
print(my_df)
cols_to_validate = ("foo", "bar")
def validate_stuff(value, notes):
# Any custom logic
if value not in ["a", "b", "x"]:
return f"FAILED {value} - PREVIOUS ({notes})"
else:
return notes
for col in cols_to_validate:
my_df = my_df.with_columns(
pl.struct([col, "notes"]).map_elements(
lambda row: validate_stuff(row[col], row["notes"])
).alias("notes")
)
print(my_df)
Run Code Online (Sandbox Code Playgroud)
我为我的Python应用程序配备了日志记录功能,它在我的Windows系统上使用Python 3.4完美运行.但是当我使用Raspbian和Python 3.2在我的Raspberry Pi上部署应用程序时,我收到以下错误:
Traceback (most recent call last):
File "aurora/aurora_websocket.py", line 265, in <module>
logging.config.fileConfig('logging.conf')
File "/usr/lib/python3.2/logging/config.py", line 70, in fileConfig
formatters = _create_formatters(cp)
File "/usr/lib/python3.2/logging/config.py", line 106, in _create_formatters
flist = cp["formatters"]["keys"]
File "/usr/lib/python3.2/configparser.py", line 941, in __getitem__
raise KeyError(key)
KeyError: 'formatters'
Run Code Online (Sandbox Code Playgroud)
logging.conf文件(以UTF-8编码,无BOM):
[loggers]
keys=root,simpleExample
[handlers]
keys=screen
[formatters]
keys=simple,complex
[logger_root]
level=NOTSET
handlers=screen
[logger_simpleExample]
level=DEBUG
handlers=screen
qualname=simpleExample
propagate=0
[handler_screen]
class=StreamHandler
level=DEBUG
formatter=complex
args=(sys.stdout,)
[formatter_simple]
format=%(asctime)s - %(levelname)s - %(message)s
datefmt=
[formatter_complex]
format=%(asctime)s - %(levelname)-8s - <%(module)s : %(lineno)d> - …Run Code Online (Sandbox Code Playgroud) 所以我刚开始学习Python并尝试制作一个程序来告诉你某一天的具体日期。我发现datetime并尝试使用它,但问题是即使密钥存在,我也会收到密钥错误。
这是我的代码:
import datetime
def day_finder(dd,mm,yy):
tags = { '1' : 'Monday' ,'2' : 'Tuesday' ,'3' : 'Wednesday' ,'4' : 'Thursday' ,'5' : 'Friday' ,'6' : 'Saturday' ,'7' : 'Sunday' }
return tags[int(datetime.datetime(yy,mm,dd).isoweekday())]
d = int(input("Enter a date"))
m = int(input("Enter a month"))
y = int(input("Enter a year"))
print (day_finder(d,m,y))
Run Code Online (Sandbox Code Playgroud) keyerror ×10
python ×9
dataframe ×2
dictionary ×2
datetime ×1
discord.py ×1
django ×1
format ×1
gensim ×1
if-statement ×1
indexing ×1
julia ×1
lazyframe ×1
logging ×1
python-3.2 ×1
python-3.x ×1
raspberry-pi ×1
word2vec ×1
youtube-dl ×1