python - use if statement to check if entry is already in a list

南楼画角 提交于 2020-03-05 03:14:14

问题


I have a list of list of float lists and I want to test if a value pair (e.g. [2.0, 1.1]) is already in this list. Therefor I wrote a simple code to check this. As far as I understand my code it should always write the result array. I think the if statement is not correct formulated or is at least not doing what I intended to do. The result array should be look like: [0, 1, 2]. It is like a 'self-check'.

import numpy as np
array_a = np.asarray([[2.0, 1.1], [3.3, 4.4], [2.5, 3.0]])
array_a_list = array_a.tolist()
result = np.zeros(np.size(array_a_list, axis=0))
for i in range(np.size(array_a_list, axis=0)):
    print(i)
    if array_a_list[i] in array_a_list: # Shouldn't this be always true? At least that's what I expect it to be.
        result[i] = array_a_list.index(i) # here I'm expecting to get the index back, where the entry is stored
test = array_a_list[i]

So the overall idea is to check if an entry is already in a list. If that's the case I want to get back the index at which the entry is stored. In my case an entry is an array of float which is looking like the following: [2.0, 1.1]. The idea came from this question.


回答1:


Got it solved. I edited the result line now:

result[i] = array_a_list.index(array_a_list[i])


来源:https://stackoverflow.com/questions/60122241/python-use-if-statement-to-check-if-entry-is-already-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!