是否可以在 "if" 语句中使用 "try" 函数?

Is it possible to use the "try" Function on an "if" statement?

在我的程序中我有这个二维数组:

Test=[
  ["TestName", "123", "1", "2.5"],
  ["NameTest", "321", "10", "5.2"],
  ["jpoj", "321", "10", "5.2"],
  ["OIAN","oihadIH","oihda","iohda"]
]

并且,在 while 循环中,在 for i in range 函数中,有这个 if 语句:

if Test[i][r]==search:

r 只是一个变量,每次迭代都会变高)。

走到这一步,如果r变量太高,就会给出一个IndexError.

有什么方法可以在上面使用 try:except() 函数吗?

这是我失败的尝试:

try:
    if Test[i][r]==search:
except(IndexError):
    r=0

完整代码在这里,如果你想看的话:

stop=False
stop2=False
import time

Test=[
  ["TestName", "123", "1", "2.5"],
  ["NameTest", "321", "10", "5.2"],
  ["jpoj", "321", "10", "5.2"],
  ["OIAN","oihadIH","oihda","iohda"]
]
r=0

search=input("Search: ")

for i in range(len(Test)):
  while stop!=True:
    try:
        if Test[i][r]==search:
          print(Test[i])
          stop=True

        else:
          try:
            r=r+1
          except(IndexError):
            r=0
    except(IndexError):
      r=0
      i=0

while stop2!=True:
  try:
    print(Test[0][r]," | ", end='')
  except IndexError:
    stop2=True
  r=r+1

如果您没有 运行 任何命令,您需要缩进 if 语句和 pass 一个空块:

try:
    if Test[i][r] == search:
        # Insert code here, and remove pass
        pass
except IndexError:
    r = 0

但您似乎 re-inventing .index() 在第一个元素上。您可以使用:

try:
    print(Test[[x[0] for x in Test].index(search)])
except ValueError:
    print(f"{search} is not in the list")

示例:

Search: TestName
['TestName', '123', '1', '2.5']
Search: Foo
Foo is not in the list

您可以将一些 QOL 方面添加到这个新方法中:

  • .strip()
    • 删除空格
  • .lower()
    • 区分大小写
  • .join()
    • 对于干净的输出
try:
    print(", ".join(Test[[x[0].lower() for x in Test].index(search.lower().strip())]))
except ValueError:
    print(f"{search} is not in the list")
Search: nametest
NameTest, 321, 10, 5.2
for row in Test:
    for item in row:
        if item == search:
            # do stuff 

这是遍历二维数组的更好方法。如果您需要获取索引,您可以添加 2 个计数器变量来跟踪它。这种方式可以防止 IndexError 而不是必须尝试捕获它。

如果您确保我们在允许的范围内,则通过条件更好地实施您的提议:

if r < len(Test[i])

如果您仍想使用 try 和 except 来执行此操作,则必须添加那些包含产生异常的异常的子句。 在这种情况下,您访问 Test[i][r] 时。别处

try: 
   a = Test[i][r]
except(IndexError):
   a = 0
   print("error")
print(a)

你为什么不简单地尝试下标 Test 矩阵...

try:
    Test[i][r]
except(IndexError):
    r=0

在这种情况下,您不需要 if

这是我的看法:

import time
stop=False
stop2=False

Test=[
  ["TestName", "123", "1", "2.5"],
  ["NameTest", "321", "10", "5.2"],
  ["jpoj", "321", "10", "5.2"],
  ["OIAN","oihadIH","oihda","iohda"]
]
r=0

search=input("Search: ")

for idx, lst in enumerate(Test):
    if search in lst:
        for index, value in enumerate(lst):
            if search == value:
                print(f"Word: {search} found in list: {idx} and index: {index}")

结果:

Search: 10
Word: 10 found in list: 1 and index: 2
Word: 10 found in list: 2 and index: 2

Search: OIAN  
Word: OIAN found in list: 3 and index: 0