2017-01-23 66 views
-1

我做以下想知道是否有可能:Python的搜索在侧名单列表

very_special = ["special"] 
my_list = ["stuff", very_special] 
if "special" in my_list: 
    print ("Found it") 

我在想,如果你能做到这一点以某种方式,不必通过整个事情的代码看,包括列表中的列表。

+0

您正在以字符串形式搜索列表。 – Harsha

回答

3

您可以通过使用递归实现这一目标。沿着这些线:

​​
-1

使用+操作

very_special = ["special"] 
my_list = ["stuff"] + very_special 
if "special" in my_list: 
    print ("Found it") 
+0

我不认为改变基准列表是他所要求的 –

0

其他用户在这里建议递归......这可能是他所要求的矫枉过正。您也可以查看项目。

very_special = ["special"] 
my_list = ["stuff", very_special] 

if "special" in my_list: 
    print("Found it") 

for item in my_list: 
    if isinstance(item, list) and "special" in item: 
     print("Found it nested inside") 
0

如果嵌套只有一个级别深,你也可以遍历每个元素外列表:

for elem in my_list: 
    if elem == "special" or (isinstance(elem, collections.Iterable) and "special" in elem): 
    print("Found it.") 

如果你想处理任意嵌套,你需要首先拼合他们(如Flatten (an irregular) list of lists):

def flatten(lst): 
    for elem in lst: 
    if isinstance(elem, collections.Iterable) and not isinstance(elem, (str, bytes)): 
     yield from flatten(elem) 
    else: 
     yield elem 

if "special" in flatten(my_list): 
    print ("Found it") 
0

对于这种情况,你需要周围的一些工作,这是一个片段来实现它。同样的方式,你可以写你自己的工作。

very_special = ["special", "v", ["xyz", "we"]] 
my_list = ["stuff", "n", very_special] 

def aggregate(newList): 
    opList = [] 
    for item in newList: 
     if list is type(item): 
      opList += aggregate(item) 
     else: 
      opList.append(item) 

    return opList 


if "special" in aggregate(my_list): 
    print ("Found it") 
0

使用原来的建议方式将无法正常工作。会员运营商in通常的行为是检查x是否为y的成员,而不会深入检查x是否也是y的任何成员的成员。

对于这种情况,对于这个具体的例子,这里是解决这个问题的一个非常具体的方法。

very_special = ["special"] 
my_list = ["stuff", very_special] 

for element in my_list: 
    if "special" in element: 
     print ("Found it") 
0

根据您的需求,下列方法可能是适当的:

import itertools 

very_special = ["special"] 
my_list = ["stuff", very_special] 

if "special" in itertools.chain.from_iterable(my_list): 
    print ("Found it") 

这使得使用Python的chain()功能的它会从被评估懒洋洋一个迭代参数链的投入。