Reputation: 181
I need some help with my code. I want to search for the element in the list of arrays when I use this:
program_button = [elem.control for elem in self.program_buttons]
positions_X = list()
positions_Y = list()
for elem in program_button:
positions_X.append(elem.getX())
positions_Y.append(elem.getY())
posX = map(str, positions_X)
posY = map(str, positions_Y)
print posX
Here is the results:
19:42:50 T:2264 NOTICE: ['25', '375', '723', '1073', '1771', '2120', '2469']
I want to search the element 723
from the list.
Can you please show me an example of how I can search the element 723
from the list using the variable called posX
?
Upvotes: 0
Views: 66
Reputation: 4685
Assuming you want to get the index of the element 723
in the list you can use :
posX.index('723')
The below convenient function can be used if the item happens to not be in the list :
def search_item(L,item):
try:
return L.index(item)
except ValueError:
return -1
Call it with print(search_item(posX,'723'))
which will return 2
in your case.
If the element is not foundable, the function will return -1.
Upvotes: 2
Reputation: 107287
You can use a generator expression within next
function :
>>> next((i for i in posX if i == '723'),None)
'723'
This will returns the variable you are searching if it exist or None
if it doesn't.
And if you want to check the existence of this value you can just use in
operand :
if `723` in Posx:
#do stuff
And if you want to return the index you can use list.index
method with a try-except
statement for handling the ValueError
or use enumerate
within preceding script :
>>> next((i for i,j in enumerate(posX) if j == '723'),None)
2
Upvotes: 1