[英]serching for nested item in nested list [python]
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]. 如何搜索嵌套列表的特定位置中的项目ex:我想在嵌套列表的第二个位置搜索项目“ny”,我的搜索必须匹配项目“ny”仅在[] [ 1]它必须忽略[3] [3]中的“ny”。
Using list comprehension: 使用列表理解:
>>> lst = [[01,"ny",100], [02,"jr",200], [03, "la", 300,"ny"]]
>>> [sublst for sublst in lst if sublst[1] == "ny"]
[[1, 'ny', 100]]
To check whether ny
exists, use any
with generator expression: 要检查是否存在
ny
,请使用带有生成器表达式的any
:
>>> any(sublist[1] == "ny" for sublist in lst)
True
>>> any(sublist[1] == "xy" for sublist in lst)
False
BTW, don't use list
as a variable name. 顺便说一句,不要使用
list
作为变量名。 It shadows builtin function list
. 它影响内置功能
list
。
UPDATE : You can also use following as suggested by @DSM. 更新 :您也可以按照@DSM的建议使用以下内容。
>>> "ny" in (sublist[1] for sublist in lst)
True
first, don't overwrite the list
built-in. 首先,不要覆盖内置
list
。
second, you can use the filter
built-in, to find all the matches: 第二,你可以使用内置的
filter
来查找所有匹配项:
list_ = [[01,"ny",100], [02,"jr",200], [03, "la", 300,"ny"]]
matches = filter(lambda element: element[1] == 'ny', list_)
exactly how you would think 你究竟怎么想
list[0][1]
EDIT: 编辑:
for inner in list:
if inner[1] == 'ny':
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.