KeyError:0,当使用python脚本读取Gmsh输出并将其转换为DNS代码会话文件时

问题描述 投票:1回答:1

当我在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)

任何帮助将不胜感激!

python dns mesh keyerror traceback
1个回答
0
投票

从上面的代码段中,我假设physidx的值将为int类型。

physidx = 0
Phys = {1: []
        }

print(Phys[physidx][0])

输出:

    print(Phys[physidx][0])
KeyError: 0

所以现在

情况1:如果您只想处理异常,则可以在异常语句中添加KeyErrorValueError并采取必要的措施。

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'}
© www.soinside.com 2019 - 2024. All rights reserved.