[英]search the list of elements from the list
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. 我想从列表中搜索元素723
。
Can you please show me an example of how I can search the element 723
from the list using the variable called posX
? 您能给我一个例子,说明如何使用posX
变量从列表中搜索元素723
吗?
Assuming you want to get the index of the element 723
in the list you can use : 假设要获取列表中元素723
的索引,可以使用:
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. 用print(search_item(posX,'723'))
调用它,在您的情况下将返回2
。
If the element is not foundable, the function will return -1. 如果找不到该元素,则该函数将返回-1。
You can use a generator expression within next
function : 您可以next
函数中使用生成器表达式:
>>> 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. 这将返回您正在搜索的变量(如果存在)或“ None
如果不存在)。
And if you want to check the existence of this value you can just use in
operand : 如果要检查此值是否存在,可以in
操作数中使用:
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 : 而且,如果您想返回索引,则可以将list.index
方法与try-except
语句一起使用来处理ValueError
或者在前面的脚本中使用enumerate
:
>>> next((i for i,j in enumerate(posX) if j == '723'),None)
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.