In my program I have this 2D array:
Test=[
["TestName", "123", "1", "2.5"],
["NameTest", "321", "10", "5.2"],
["jpoj", "321", "10", "5.2"],
["OIAN","oihadIH","oihda","iohda"]
]
And, in a while
loop, in a for i in range
function, there's this if
statement:
if Test[i][r]==search:
(r
is just a variable that gets higher each while iteration).
When it gets to this point, if the r
variable is too high, it gives an IndexError
.
Is there a way I can use something like the try:
and except()
functions on it?
Here was my failed attempt at it:
try:
if Test[i][r]==search:
except(IndexError):
r=0
The whole code is here if you wish to see it:
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
CodePudding user response:
for row in Test:
for item in row:
if item == search:
# do stuff
This is a better way to loop through a 2d array. If you need to get the index you could add 2 counter variables to track it. This way prevents the IndexError rather than having to try catch it.
CodePudding user response:
A better implementation of what you propose is through a condition if you make sure that we are within the allowed range:
if r < len(Test[i])
If you still want to do it with try and except you must add those clauses enclosing the exception in which the exception is produced. In this case at the time you access Test[i][r]. NOT ELSEWHERE
try:
a = Test[i][r]
except(IndexError):
a = 0
print("error")
print(a)
CodePudding user response:
Why don't you simply try to subscript the Test
matrix...
try:
Test[i][r]
except(IndexError):
r=0
You don't need the if
in this case.
CodePudding user response:
You have need to indent your if
statement and pass
an empty block if you aren't running any commands:
try:
if Test[i][r] == search:
# Insert code here, and remove pass
pass
except IndexError:
r = 0
But it seems you're re-inventing .index()
on the first element. You can use:
try:
print(Test[[x[0] for x in Test].index(search)])
except ValueError:
print(f"{search} is not in the list")
Examples:
Search: TestName
['TestName', '123', '1', '2.5']
Search: Foo
Foo is not in the list
You could add some QOL aspects to this new method:
.strip()
- To remove whitespace
.lower()
- To be case intensive
.join()
- For a clean output
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
CodePudding user response:
This is my take on this:
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}")
Results:
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