搜索列表的序列

时间:2016-04-12 10:33:10

标签: python list parsing

listIf我有一个列表列表。每个子列表与下一个子列表不同,有时甚至是空的。

    list[0]=['This','is','the','sequence']
    list[1]=['This','is','another','sequence']
    list[2]=[]
    list[n]=[a,b,c,d]

如何搜索列表并正确识别list [n]何时发生。 (IE识别a,b,c然后提取d。)

我试过

for lists in my_list[1:]:
          if not lists:
             continue
          if (lists[0]=='a') & (lists[1]=='b') &(lists[2]=='c'):
             extracted_variable = lists[3]

但是我收到空列表的'列表索引超出范围'。哪些功能对我有利?

3 个答案:

答案 0 :(得分:0)

答案:

for l in lists:
    if l[:3] == ['a', 'b', 'c'] and len(l) > 3:
        print l[3]

说明:

在空列表中获得“列表索引超出范围”的原因是因为您尝试访问超出范围的索引(列表[0] =='a')。我使用的语法l[:3]为您提供了包含前3项的列表的子列表。例如,此[1,2,3,4][:3]将返回此[1,2,3]。 对于空列表,没有问题,因为它只会返回一个空列表。

因此,按照我上面使用的方式,我们只需要一个包含3个项目的子列表,然后检查它是否为["a", "b", "c"]列表。如果是这样,我们确保列表中至少还有一个项目(通过检查列表的len()),如果是,我们打印它。

此外,您不应在代码中使用关键字“list”作为变量名称,但我认为它可能只是问题的一个示例。

您应该阅读有关python中列表以及如何使用它们的更多信息(http://www.tutorialspoint.com/python/python_lists.htm

答案 1 :(得分:0)

首先检查列表长度是否大于2并应用您的检查条件如下: 使用for循环:

<div id="NavBar">
  <ul>
    <li><a id="Hjem" href="index.html">Hjem</a>
    </li>
    <li><a id="Olie" href="olie.html">Olie</a>
    </li>
    <li><a id="Kul" href="kul.html">Kul</a>
    </li>
    <li><a id="Naturgas" href="naturgas.html">Naturgas</a>
    </li>
  </ul>
</div>

使用列表理解:

my_list = [['This', 'is', 'the', 'sequence'], ['This', 'is', 'another', 'sequence'], [], ['a', 'b', 'c', 'd']]
for lst in my_list:
    if len(lst) > 2 and lst[0] == 'a' and lst[1] == 'b' and lst[2] == 'c':
        extracted_variable = lst[3]
        print extracted_variable

输出:

my_list = [['This', 'is', 'the', 'sequence'], ['This', 'is', 'another', 'sequence'], [], ['a', 'b', 'c', 'd']]
a = [lst[3:] for lst in my_list if len(lst) > 2 and lst[0] == 'a' and lst[1] == 'b' and lst[2] == 'c']
print a[0][0]

希望这有助于:)

答案 2 :(得分:0)

您可以应用滑动/滚动窗口的技术:

from itertools import islice

all_lists = [

    [1,2,3],
    [4,5,6,5,4,7,8],
    [7,8,9,4,4],
    [1,],
    ["a","b","c"],

]

## All the lists you want to find
## We use tuples becuase lists are not hashable. You also can do this tuple([1,2,3])
target_list_1 = ("a","b","c")
target_list_2 = (1,2,3)

## A counter for your target lists you want to find
counter_dict = {
    target_list_1 : 0,
    target_list_2 : 0,
}


generator = islice(all_lists, len(all_lists) )

for item in generator:

    ## You can add as many checking conditions as you want, you may 
    ## also use switch statment here, whatever you want

    if item == list(target_list_1):
        counter_dict[target_list_1] +=1

    if item == list(target_list_2):
        counter_dict[target_list_2] +=1


print counter_dict

输出:

{ 
    ('a', 'b', 'c') : 1, 
    (1, 2, 3)       : 1
}