简体   繁体   English

给定字符串列表在其他列表中查找索引

[英]Given list of string find the index in other list

I have two list: 我有两个清单:

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

Given the strings in z1_wanted I want to get the index of the strings in items , returning 鉴于z1_wanted的字符串,我想获取items字符串的索引,返回

   [0, 2, 4]

How can I achieve that? 我怎样才能做到这一点?

Update: corrected the index 更新:更正了索引

You can use list comprehension, like this 你可以像这样使用列表理解

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

You can also use map function, like this 你也可以像这样使用map功能

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

Remember index function will throw an error if the item is not found in items . 如果在item中找不到items 请记住 index函数将抛出错误。

If you want to do the reverse of this, then you can do 如果你想做相反的事情,那么你可以这样做

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

Here is another way using list comprehension and enumerate: 这是使用列表理解和枚举的另一种方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM