搜索列表列表中的元素

时间:2014-07-12 10:30:56

标签: python list sublist

我有一个列表:

list=[[lsn,tid,status,type,item,AFIM,BFIM],[1,1,Active,Read,X,-,-],[2,1,Active,Write,X,2,0],....and so on]

现在我有一个变量

tid=1

我想在' list'中搜索该列表tid匹配和状态应该是'写'。我是这样尝试但根本没有结果......

for id, stat in list/enumerate(list):
    if id == tid and stat == 'Write':
        print list

拆分列表有帮助吗?

2 个答案:

答案 0 :(得分:2)

你的意思是这样吗?

l = [["lsn","tid","status","type","item","AFIM","BFIM"],
     [1,1,"Active","Read","X","-","-"],
     [2,1,"Active","Write","X","2","0"]]

for row in l:
    if row[1] == 1 and row[3] == 'Write':
        print(row)

# will print ...
# [2, 1, 'Active', 'Write', 'X', '2', '0']

您也可以使用namedtuples

import collections
Row = collections.namedtuple('Row', 'lsn tid status type item AFIM BFIM')

for row in map(lambda row: Row(*row), l):
    if row.tid == 1 and row.type == 'Write':
        print(row)

# will print ...
# Row(lsn=2, tid=1, status='Active', type='Write', item='X', AFIM='2', BFIM='0')

答案 1 :(得分:0)

不,分裂确实没有帮助。

您可以使用list comprehensions和动态named tuples

from collections import namedtuple

lst = [["lsn","tid","status","type","item","AFIM","BFIM"],
       [1,1,"Active","Read","X","-","-"],
       [2,1,"Active","Write","X","2","0"]]

Data = namedtuple('Data', lst[0])
rows = [Data(*row) for row in lst[1:]]
print [data for data in rows if data.tid == 1 and data.type == 'Write']

# Prints [Data(lsn=2, tid=1, status='Active', type='Write', item='X', AFIM='2', BFIM='0')]

注释

  • 正如有人已经提到的那样,最好不要在内置list之后调用变量 - 这通常会导致混淆或错误。