KeyError:0 when using a python script to read and convert Gmsh output to a DNS code session file
KeyError:0 when using a python script to read and convert Gmsh output to a DNS code session file
当我 运行 Gmsh 输出文件上的 python 脚本时,出现以下错误:
Traceback (most recent call last):
File "/Users/ali/bin/gmsh2sem.py", line 289, in <module>
surflines += "\t% 4i % 4i %i <B> %s </B>\n" % (i, elmt+1, edge+1, Phys[physidx][0])
KeyError: 0
它引用的 python 代码部分是:
if len(Phys):
# -- SURFACES section from read BC
# Now that we know all quads, we can match BC to surfaces
# FIXME: surfaces list is unsorted
surflines = ""
i = 0
for line in rawsurf:
words = line.split()
physidx = int(words[version.physidx_col])
try:
elmt, edge = find_element_and_edge(Elements, int(words[-2]), int(words[-1]))
i += 1
surflines += "\t% 4i % 4i %i <B> %s </B>\n" % (i, elmt+1, edge+1, Phys[physidx][0])
except ValueError:
sys.stderr.write("ignoring unmatched nodes %s" % line)
任何帮助将不胜感激!
根据你上面的代码片段,我假设 physidx
的值是 int 类型。
physidx = 0
Phys = {1: []
}
print(Phys[physidx][0])
输出:
print(Phys[physidx][0])
KeyError: 0
所以现在
案例 #1:如果您只想处理异常,您可以在异常语句中添加 KeyError
和 ValueError
并采取必要的措施。
try:
print(Phys[physidx][0])
except (ValueError,KeyError) as err:
print("Key error ", err)
案例 #2:如果您有一些默认值,那么您可以使用 .get
方法。
print(Phys.get(physidx, [{"default value"}])[0])
# output on missing key
# {'default value'}
当我 运行 Gmsh 输出文件上的 python 脚本时,出现以下错误:
Traceback (most recent call last):
File "/Users/ali/bin/gmsh2sem.py", line 289, in <module>
surflines += "\t% 4i % 4i %i <B> %s </B>\n" % (i, elmt+1, edge+1, Phys[physidx][0])
KeyError: 0
它引用的 python 代码部分是:
if len(Phys):
# -- SURFACES section from read BC
# Now that we know all quads, we can match BC to surfaces
# FIXME: surfaces list is unsorted
surflines = ""
i = 0
for line in rawsurf:
words = line.split()
physidx = int(words[version.physidx_col])
try:
elmt, edge = find_element_and_edge(Elements, int(words[-2]), int(words[-1]))
i += 1
surflines += "\t% 4i % 4i %i <B> %s </B>\n" % (i, elmt+1, edge+1, Phys[physidx][0])
except ValueError:
sys.stderr.write("ignoring unmatched nodes %s" % line)
任何帮助将不胜感激!
根据你上面的代码片段,我假设 physidx
的值是 int 类型。
physidx = 0
Phys = {1: []
}
print(Phys[physidx][0])
输出:
print(Phys[physidx][0])
KeyError: 0
所以现在
案例 #1:如果您只想处理异常,您可以在异常语句中添加 KeyError
和 ValueError
并采取必要的措施。
try:
print(Phys[physidx][0])
except (ValueError,KeyError) as err:
print("Key error ", err)
案例 #2:如果您有一些默认值,那么您可以使用 .get
方法。
print(Phys.get(physidx, [{"default value"}])[0])
# output on missing key
# {'default value'}