2014-03-30 46 views
0

索引我有两个列表:定字符串的列表中找到其他列表

items = ['SZ1/SS1', 'ZZ1/ZS1', 'ZS1/SS1', 'ZZ1/SZ1', 'ZZ1/SS1', 'SZ1/ZS1'] 
z1_wanted = ["SZ1/SS1", "ZS1/SS1", "ZZ1/SS1"] 

鉴于我想要得到的字符串的索引items的字符串z1_wanted, 返回

[0, 2, 4] 

我该如何实现这一目标?

更新:修正后的指数

+0

你的索引是错误的,应该不会吧是'[0,1,3]' – sshashank124

+1

'SZ1/SS1'的索引是'0',而不是'1' – thefourtheye

回答

1

您可以使用列表理解,这样

print [items.index(item) for item in z1_wanted] 
# [0, 2, 4] 

您还可以使用map功能,这样

print map(items.index, z1_wanted) 
# [0, 2, 4] 

记住index函数会抛出一个错误,如果在items中找不到item

如果你想要做的这种反向,那么你可以

myid = [1,3,4] 
print [items[item] for item in myid] 
# ['ZZ1/ZS1', 'ZZ1/SZ1', 'ZZ1/SS1'] 
+0

感谢百万,还有一件事。鉴于索引列表如何返回值?例如'myid = [1,3,4]',我想获得'items'的成员,返回'['ZZ1/ZS1','ZZ1/SZ1','ZZ1/SS1']' – neversaint

+1

@neversaint请检查更新的答案。 – thefourtheye

1

这里使用列表理解和枚举另一种方式做到:

>>> [i for i, j in enumerate(items) if j in z1_wanted ] 
[0, 2, 4] 
>>>