简体   繁体   中英

Find first position of values in list

If I have a list of 1's and 2's, how can I find the first index of 1 and 2.

For example [1,1,1] should output (0,-1) , where -1 represents not in the list and [1,2,1] should output (0,1) , [1,1,1,2] should output (0,3) .

One way would be to create a separate list for items to look index for and use index function and using list comprehension ( also additional check is made to make sure item is in list else ValueError will occur ):

my_list = [1,1,1]
items = [1,2]
print ([my_list.index(item) if item in my_list  else -1 for item in items])

Output:

[0, -1]

If tuple is needed then the above list can be converted into tuple using tuple function:

tuple([my_list.index(item) if item in my_list else -1 for item in items])

In longer way without using list comprehension :

my_list = [1,1,1]
items = [1,2]
# create empty list to store indices
indices = []

# iterate over each element of items to check index for
for item in items:
    # if item is in list get index and add to indices list
    if item in my_list:
        item_index = my_list.index(item)
        indices.append(item_index)
    # else item is not present in list then -1 
    else:
        indices.append(-1)

print(indices)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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