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].
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:
>>> 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. It shadows builtin function list
.
UPDATE : You can also use following as suggested by @DSM.
>>> "ny" in (sublist[1] for sublist in lst)
True
first, don't overwrite the list
built-in.
second, you can use the filter
built-in, to find all the matches:
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':
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.