在列表中搜索元素

2024-09-28 23:00:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个清单:

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匹配的列表,状态应该是“Write”。我试着这样做,但没有任何结果。。。。。你知道吗

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

拆分列表有帮助吗??你知道吗


Tags: andid列表readtypestatusitemstat
2条回答

不,分开也没用。你知道吗

可以使用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这样的内置函数之后调用变量—这通常会导致混淆或bug。你知道吗

你是说这样的事吗?你知道吗

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')

相关问题 更多 >