简体   繁体   English

查找列表中相同元素的索引号

[英]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' . 问题在于字符串与'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: 不幸的是,从由252个元素组成的初始列表中,输出如下:

[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. 您可以使用enumerate()内置函数来获取列表中每个字符串的索引值。 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 . 这将打印lists_and_strings中每个字符串元素的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]

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

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