Python:查找数组中元素的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27260811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: find position of element in array
提问by julesjanker
I have a CSV containing weather data like max and min temperatures, precipitation, longitude and latitude of the weather stations etc. Each category of data is stored in a single column.
我有一个 CSV 包含天气数据,如最高和最低温度、降水、气象站的经度和纬度等。每一类数据都存储在一个列中。
I want to find the location of the maximum and minimum temperatures. Finding the max or min is easy: numpy.min(my_temperatures_column)
我想找到最高和最低温度的位置。找到最大值或最小值很容易: numpy.min(my_temperatures_column)
How can I find the position of where the min or max is located, so I can find the latitude and longitude?
如何找到最小值或最大值所在的位置,以便找到纬度和经度?
Here is my attempt:
这是我的尝试:
def coldest_location(data):
coldest_temp= numpy.min(mean_temp)
for i in mean_temp:
if mean_temp[i] == -24.6:
print i
Error: List indices must be int
错误:列表索引必须是 int
I saved each of the columns of my CSV into variables, so they are all individual lists.
我将 CSV 的每一列保存到变量中,因此它们都是单独的列表。
lat = [row[0] for row in weather_data] # latitude
long = [row[1] for row in weather_data] # longitude
mean_temp = [row[2] for row in weather_data] # mean temperature
I have resolved the problem as per the suggestion list.index(x)
我已经按照建议 list.index(x) 解决了这个问题
mean_temp.index(coldest_temp)
coldest_location=[long[5],lat[5]]
Unsure if asking a second question within a question is proper, but what if there are two locations with the same minimum temperature? How could I find both and their indices?
不确定在问题中问第二个问题是否合适,但如果有两个位置的最低温度相同怎么办?我怎么能找到它们和它们的索引?
采纳答案by Aaron
Have you thought about using Python list's .index(value)
method? It return the index in the list of where the first instance of the value
passed in is found.
你有没有想过使用Python list的.index(value)
方法?它返回列表中找到第一个value
传入实例的位置的索引。
回答by Marcin
Without actually seeing your data it is difficult to say how to find location of max and min in your particular case, but in general, you can search for the locations as follows. This is just a simple example below:
如果没有实际看到您的数据,很难说出如何在您的特定情况下找到最大值和最小值的位置,但通常,您可以按如下方式搜索位置。这只是下面的一个简单示例:
In [9]: a=np.array([5,1,2,3,10,4])
In [10]: np.where(a == a.min())
Out[10]: (array([1]),)
In [11]: np.where(a == a.max())
Out[11]: (array([4]),)
Alternatively, you can also do as follows:
或者,您也可以执行以下操作:
In [19]: a=np.array([5,1,2,3,10,4])
In [20]: a.argmin()
Out[20]: 1
In [21]: a.argmax()
Out[21]: 4
回答by Gary02127
As Aaron states, you can use .index(value)
, but because that will throw an exception if value
is not present, you should handle that case, even if you're sure it will never happen. A couple options are by checking its presence first, such as:
正如 Aaron 所说,您可以使用.index(value)
,但是因为如果value
不存在就会抛出异常,所以您应该处理这种情况,即使您确定它永远不会发生。有几个选项是首先检查它的存在,例如:
if value in my_list:
value_index = my_list.index(value)
or by catching the exception as in:
或者通过捕获异常,如下所示:
try:
value_index = my_list.index(value)
except:
value_index = -1
You can never go wrong with proper error handling.
正确的错误处理永远不会出错。
回答by sudhakar
You should do:
你应该做:
try:
value_index = my_list.index(value)
except:
value_index = -1;
回答by Nishant Dixit
I would assume your variable mean_temp already has the values loaded in to it and is nX1 dimension (i.e only one row). Now to achieve what you want, you can :
我会假设你的变量 mean_temp 已经加载了值并且是 nX1 维度(即只有一行)。现在要实现您想要的,您可以:
Change the datatype of your variable:
更改变量的数据类型:
def coldest_location(data):
mean_temp = numpy.mat(mean_temp) #data is now matrix type
min_index = numpy.nonzero(mean_temp == mean_temp.min()) # this returns list of indexes
print mean_temp[min_index[0],min_index[1]] # printing minimum value, i.e -24.6 in you data i believe
回答by lkolololol
There is a built in method for doing this:
有一个内置的方法可以做到这一点:
numpy.where()
You can find out more about it in the excellent detailed documentation.
您可以在优秀的详细文档中找到有关它的更多信息。
回答by Haris Np
Suppose if the list is a collection of objects like given below:
假设列表是一个对象的集合,如下所示:
obj = [
{
"subjectId" : "577a54c09c57916109142248",
"evaluableMaterialCount" : 0,
"subjectName" : "ASP.net"
},
{
"subjectId" : "56645cd63c43a07b61c2c650",
"subjectName" : ".NET",
},
{
"subjectId" : "5656a2ec3c43a07b61c2bd83",
"subjectName" : "Python",
},
{
"subjectId" : "5662add93c43a07b61c2c58c",
"subjectName" : "HTML"
}
]
You can use the following method to find the index. Suppose the subjectId is 5662add93c43a07b61c2c58c then to get the index of the object in the list,
您可以使用以下方法查找索引。假设 subjectId 是 5662add93c43a07b61c2c58c 然后获取列表中对象的索引,
subjectId = "5662add93c43a07b61c2c58c"
for i, subjobj in enumerate(obj):
if(subjectId == subjobj['subjectId']):
print(i)
回答by atlas
For your first question, find the position of some valuein a list xusing index(), like so:
对于您的第一个问题,使用 index()在列表x 中找到某个值的位置,如下所示:
x.index(value)
For your second question, to check for multiple same values you should split your list into chunks and use the same logic from above. They say divide and conquer. It works. Try this:
对于您的第二个问题,要检查多个相同的值,您应该将列表分成多个块并使用与上面相同的逻辑。他们说分而治之。有用。尝试这个:
value = 1
x = [1,2,3,4,5,6,2,1,4,5,6]
chunk_a = x[:int(len(x)/2)] # get the first half of x
chunk_b = x[int(len(x)/2):] # get the rest half of x
print(chunk_a.index(value))
print(chunk_b.index(value))
Hope that helps!
希望有帮助!