0

this is my nested list

list = [[01,"ny",100], [02,'jr",200], [03, "la", 300,"ny"]]

My Question is:

how to search for an item in the a specific position of nested list ex: i want to search for the item "ny" in the 2nd position of nested list means, my search has to match the item "ny" in only [][1] position it has to ignore "ny" in [3][3].

4

3 回答 3

3

使用列表理解:

>>> lst  = [[01,"ny",100], [02,"jr",200], [03, "la", 300,"ny"]]
>>> [sublst for sublst in lst if sublst[1] == "ny"]
[[1, 'ny', 100]]

要检查是否ny存在,请使用any生成器表达式:

>>> any(sublist[1] == "ny" for sublist in lst)
True
>>> any(sublist[1] == "xy" for sublist in lst)
False

顺便说一句,不要list用作变量名。它隐藏了内置函数list

更新:您也可以按照@DSM 的建议使用以下内容。

>>> "ny" in (sublist[1] for sublist in lst)
True
于 2013-11-14T01:57:31.363 回答
0

首先,不要覆盖list内置。

其次,您可以使用filter内置的,查找所有匹配项:

list_ = [[01,"ny",100], [02,"jr",200], [03, "la", 300,"ny"]]
matches = filter(lambda element: element[1] == 'ny', list_)
于 2013-11-14T01:52:27.857 回答
-1

你会怎么想

list[0][1]

编辑:

for inner in list:
    if inner[1] == 'ny':
        ...
于 2013-11-14T01:51:05.023 回答