问题描述
这是我的嵌套列表
list = [[01,"ny",100],[02,'jr,200],[03," la,300," ny]]
我的问题是:
如何在嵌套列表的特定位置搜索项目例如:我想在嵌套列表的第二个位置搜索项目"ny"意味着,我的搜索必须仅在[] [1]位置匹配项目"ny",而在[3] [3]中必须忽略"ny".
使用列表理解:
>>>lst = [[01,"ny",100],[02,"jr",200],[03,"la",300,"ny"]]>>>[如果sublst [1] =="ny",则替换为lst中的sublst][[1,'ny',100]]
要检查是否存在 ny
,请使用 any
具有生成器表达式:
>>>任何(sublist [1] =="ny"表示lst中的子列表)真的>>>任何(sublist [1] =="xy"表示lst中的子列表)错误的
顺便说一句,不要使用 list
作为变量名.它隐藏了内置函数 list
..>
更新:您也可以按照@DSM的建议使用以下内容.
>>>(在第一个子列表的子列表[1]中为"ny")真的
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 listex: i want to search for the item "ny" in the 2nd position of nested listmeans, 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
这篇关于在嵌套列表中为嵌套项进行搜索[python]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!