I have list like this: listvalues = [True, True, False, True, False, 24, somestring, 50]
So the first five elements of the list are booleans, the rest are strings and ints.
Now I want to check the first five elements if they are true or false, and if they are true,
I want to use a certain method, depending on the index of the element.
So, in the case above, one action should be made for the first element (index 0), then another action for the second element (index 1), then another action for the forth element.
If all of the booleans are false a warning should appear.
Sorry for the noob question, but I couldn't find a short and easy solution by myself...
5 Answers
There are a number of things that might help here. First off, you should use list slicing to isolate the booleans. If you know the first 5 elements are what you're after, then myList[0:5] will get just those and ignore the others.
Next, look into the any function. It'll return True if any of the elements is True, so you might do this to decide if you need to issue the warning:
if not any(myList[0:5]):
# Code here to issue the warning.
Next, to deal with which functions to call, you'd probably want something like this:
funcList = [f0, f1, f2, f3, f4]
for idx, test in enumerate(myList[0:5]):
if test: funcList[idx]()
Ideally though, what would probably work better would be to put references to the individual functions in the original list, instead of booleans, with a value of None if you wanted to skip that function. Your original list would end up looking like this:
myList = [f1, f2, None, f3, None, 24, "string", 50]
To call the ones that you want to call you'd do this:
for func in myList[0:5]:
if func is not None: func()
1 Comment
Given you already defined the functions you want to apply for each case, you can put them in a list to call them in the loop
perform = [func1, func2, func3, func4, func5]
if not any(listvalues[:5]): raise Exception
for index in range(5):
if listvalues[index]:
func = perform[index]
func()
2 Comments
adict = dict(1=a), adict = dict(one=a) and adict = {1:'a'} was making some wrong connections on my brainif your_list[:5] == [False,False,False,False,False]:
print 'warning'
else:
method1(your_list[0])
method2(your_list[1])
method3(your_list[2])
method4(your_list[3])
method5(your_list[4])
def method1(myBool):
if myBool == False:
return
--- method content ---
def method2(myBool):
if myBool == False:
return
--- method content ---
...
Would be my solution.
enumerate. If that's not what was tripping you up, consider adding some detail about what you tried and what aspect of this you can't figure out.listvalues = [True, True, False, True, False, 24, "somestring", 50]