简体   繁体   中英

Find index number for identical elements in a list

I have a list made of lists and strings. I want to find the index position of every element in the list which is a string. The problem is that the strings are identical to 'Error' . I tried with the following code:

err = [bayesian_prices.index(i) for i in bayesian_prices if i == 'Error']

Unfortunately, from the initial list composed by 252 elements, the output is the following:

[39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 
39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 
39, 39, 39, 39]

This is exactly the position of the first element which is not a list, but a string. Then the other string positions are registered with the same index number. Probably is due to the fact that all the strings are equal. How it is possible to obtain the correct index numbers?

You can use the enumerate() builtin function to get the index value of every string in a list. Here is an example:

lists_and_strings = [[1, 2, 3], 'hello', [3, 4], 'error', [4, 5, 6]]

for index, element in enumerate(lists_and_strings):
    if type(element) is str:
        print(index)

This will print the index of every string element in lists_and_strings .

For variety here is another way:

lists_and_strings = [[1, 2, 3], 'hello', [3, 4], 'error', [4, 5, 6]]

str_indices = [i for i, j in enumerate(map(type, lists_and_strings)) if j is str]

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