查找多个列表

时间:2017-07-26 10:39:08

标签: python arrays list python-3.x arraylist

我有3个阵列l1,l2& l3和列表中的每个元素在3个列表中是唯一的。我有另一个数组q,其值需要在数组l1,l2和amp;中检查。 l3如果它存在则应该输出数组名称

注意:q的值可能介于l1,l1或l3

之间

示例列表:

q= ['abc','def','ghi',' gggg','cc ']
l1 = ['aa abc','bb bb','cc cc']
l2 = ['ddd ddd','eee def eee','fff fff']
l3 = ['gggg gggg','hhhh hhhh','ghi iiii']

代码应该是这样的

for value in q
  if value  in l1:
    do something
  elif value  in l2:
    do something
  elif value  in l2:
    do something
  else:
    "nil"

输出应该是:

l1
l2
l3
l3
l1

提前致谢..

2 个答案:

答案 0 :(得分:1)

由于您正在处理子字符串,因此需要检查每个列表中的各个元素:

q = ['abc','def','ghi',' gggg','cc ']
l1 = ['aa abc','bb bb','cc cc']
l2 = ['ddd ddd','eee def eee','fff fff']
l3 = ['gggg gggg','hhhh hhhh','ghi iiii']
all_lists = [l1, l2, l3]

for val in q:
    for i, li in enumerate(all_lists):
        for li_val in li:
            if val in li_val:
                print('{} is in l{}'.format(val, i + 1))

输出:

abc is in l1
def is in l2
ghi is in l3
 gggg is in l3
cc  is in l1

请注意,您无法直接访问列表的名称,因为对象无法跟踪引用它们的名称。您可以使用字典,但名称仍然需要硬编码。

答案 1 :(得分:0)

试试这个

q= ['abc','def','ghi',' gggg','cc ']
l1 = ['abc','bb bb','cc cc']
l2 = ['ddd ddd','eee def eee','fff fff']
l3 = ['gggg gggg','hhhh hhhh','ghi iiii']

for stri in (q):
    for i,l in enumerate([l1,l2,l3]):
        if(filter(lambda x:stri in x, l)):
            print stri +" found in l"+str(i+1)