Python在数组Lis中搜索字符串

2024-10-03 13:20:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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)如何在PageNumList中搜索NR0951113?在

已编辑

2)如果我想得到NR0951113数组索引?如何得到它?在


Tags: innode编辑数组namedtupleprintappenddeviceid
1条回答
网友
1楼 · 发布于 2024-10-03 13:20:48

我想你可能想要:

any(x.DeviceID == 'NR0851113' for x in PageNumList)

如果您确实想获得索引,那么^{}可能是您应该使用的内置项:

^{pr2}$

如果在任何对象上找不到设备ID,则将引发StopIteration。您可以通过向next传递第二个值来防止StopIteration,如果传入的iterable为空,则返回该值:

index = next((i for i,x in enumerate(PageNumList) if x.DeviceID == 'NR085113'),None)
if index is not None:
    ...

相关问题 更多 >