我有以下两个列表:
# List of tuples representing the index of resources and their unique properties
# Format of (ID,Name,Prefix)
resource_types=[('0','Group','0'),('1','User','1'),('2','Filter','2'),('3','Agent','3'),('4','Asset','4'),('5','Rule','5'),('6','KBase','6'),('7','Case','7'),('8','Note','8'),('9','Report','9'),('10','ArchivedReport',':'),('11','Scheduled Task',';'),('12','Profile','<'),('13','User Shared Accessible Group','='),('14','User Accessible Group','>'),('15','Database Table Schema','?'),('16','Unassigned Resources Group','@'),('17','File','A'),('18','Snapshot','B'),('19','Data Monitor','C'),('20','Viewer Configuration','D'),('21','Instrument','E'),('22','Dashboard','F'),('23','Destination','G'),('24','Active List','H'),('25','Virtual Root','I'),('26','Vulnerability','J'),('27','Search Group','K'),('28','Pattern','L'),('29','Zone','M'),('30','Asset Range','N'),('31','Asset Category','O'),('32','Partition','P'),('33','Active Channel','Q'),('34','Stage','R'),('35','Customer','S'),('36','Field','T'),('37','Field Set','U'),('38','Scanned Report','V'),('39','Location','W'),('40','Network','X'),('41','Focused Report','Y'),('42','Escalation Level','Z'),('43','Query','['),('44','Report Template ','\\'),('45','Session List',']'),('46','Trend','^'),('47','Package','_'),('48','RESERVED','`'),('49','PROJECT_TEMPLATE','a'),('50','Attachments','b'),('51','Query Viewer','c'),('52','Use Case','d'),('53','Integration Configuration','e'),('54','Integration Command f'),('55','Integration Target','g'),('56','Actor','h'),('57','Category Model','i'),('58','Permission','j')]
# This is a list of resource ID's that we do not want to reference directly, ever.
unwanted_resource_types=[0,1,3,10,11,12,13,14,15,16,18,20,21,23,25,27,28,32,35,38,41,47,48,49,50,57,58]
我正在尝试比较两者,以便构建第三个列表,其中包含当前存在于 unwanted_resource_types 中的每个唯一资源类型的“名称”。例如最终的结果列表应该是: result = ['Group','User','Agent','ArchivedReport','ScheduledTask','...','...']
我已经尝试了以下(我认为)应该有效的方法:
result = []
for res in resource_types:
if res[0] in unwanted_resource_types:
result.append(res[1])
当未能填充 result 时,我也尝试过:
result = []
for res in resource_types:
for type in unwanted_resource_types:
if res[0] == type:
result.append(res[1])
也无济于事。有什么我想念的吗?我相信这是执行列表理解的正确位置,但这仍然在我完全理解的灰色篮子中(在这种情况下,Python 文档对我来说有点过于简洁)。
我也愿意完全重新考虑这个问题,但我确实需要保留元组列表,因为它在脚本的其他地方使用过。感谢您提供的任何帮助。
请您参考如下方法:
您的资源类型正在使用字符串,而您不需要的资源正在使用整数,因此您需要进行一些转换才能使其正常工作。
试试这个:
result = []
for res in resource_types:
if int(res[0]) in unwanted_resource_types:
result.append(res[1])
或使用列表理解:
result = [item[1] for item in resource_types if int(item[0]) in unwanted_resource_types]
