[英]Python Search The String in a Array List
StructPageNum = namedtuple('FDResult', ['DeviceID', 'PageNum'])
PageNumList = []
Node = StructPageNum(DeviceID='NR0951113', PageNum=[1,2,3,4])
PageNumList.append(Node)
Node = StructPageNum(DeviceID='NR0951114', PageNum=[1,2,3,4])
PageNumList.append(Node)
print('NR0951113' in PageNumList[:].DeviceID)
1)how to search NR0951113 whether in the PageNumList or not? 1)如何在PageNumList中搜索NR0951113?
2)if i want to get the NR0951113 array index?how to get it? 2)如果我想获取NR0951113数组索引?如何获取?
I think you probably want: 我想您可能想要:
any(x.DeviceID == 'NR0851113' for x in PageNumList)
If you actually want to get the index, then possibly next
is the builtin you should be using: 如果你真的想要得到的指数,则有可能next
就是你应该使用内置:
next(i for i,x in enumerate(PageNumList) if x.DeviceID == 'NR085113')
This will raise StopIteration
if the DeviceID isn't found on any of your objects. 如果在您的任何对象上都找不到DeviceID,这将引发StopIteration
。 You can prevent the StopIteration
by passing a second value to next
which is returned if the iterable you pass in is empty: 您可以通过将第二个值传递给next
来防止StopIteration
,如果传入的可迭代项为空,则返回第二个值:
index = next((i for i,x in enumerate(PageNumList) if x.DeviceID == 'NR085113'),None)
if index is not None:
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.