我有一个列表:
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
拆分列表有帮助吗?
答案 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
之后调用变量 - 这通常会导致混淆或错误。