I have a code like that,
i = 0
l1 = ['a','b','c']
while(i < len(l1)):
if i 2 < len(l1):
if l1[i 2] == 'c':
print("ok")
else:
print("None,Error!")
else:
print("None,Error!")
i = 1
As you can see, in the else
part, print("None,Error!")
are used in two times. In practice, they are very long but totally same so I want to merge them to make them simple.However, I need to check if i 2
is out of list bound, so I cannot rewrite it to
if i 2 < len(l1) and l1[i 2] == 'c':
Is there any idea can solve this problem?
CodePudding user response:
As Phu Ngo mentions, we can take advantage of short circuiting to write
i = 0
l1 = ['a','b','c']
while(i < len(l1)):
if i 2 < len(l1) and l1[i 2]=='c':
print("ok")
else:
print("None,Error!")
i =1
If i 2<len(l1)
is false, then the expression l1[i 2]=='c'
is never evaluated, which means that no error is raised.
Another solution that can be considered here is a try/except clause.
i = 0
l1 = ['a','b','c']
while(i < len(l1)):
try:
if l1[i 2]=='c':
print("ok")
else:
raise ValueError
except Exception:
print("None,Error!")
i =1
Both result in the printouts
ok
None,Error!
None,Error!
CodePudding user response:
Unless your data is large, ditch the algorithmic details and just arrange the data in a convenient way:
xs = ['a', 'b', 'c']
for x1, x2 in zip(xs, xs[2:] [None, None]):
print("ok" if x2 == 'c' else "None,Error!")
Yet another illustration of the general point: one rarely needs to iterate over a collection via indexes.