在python列表中找到最小的数字并打印位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14423363/
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
Find the smallest number in a python list and print the position
提问by Kit Yeung
I have a list of integer imported via a file
我有一个通过文件导入的整数列表
xy = [50, 2, 34, 6, 4, 3, 1, 5, 2]
I am aware of Python: finding lowest integer
However, I wonder how can I print the position of it instead of just finding the smallest number?
但是,我想知道如何打印它的位置而不仅仅是找到最小的数字?
采纳答案by Volatility
Just use the list.indexmethod:
只需使用以下list.index方法:
print xy.index(min(xy))
# 6
If the minimum is repeated, you'll only get the index of the first occurrence, though.
但是,如果重复最小值,则只会获得第一次出现的索引。
回答by sidi
indices = [i for i, x in enumerate(xy) if x == min(xy)] # Indices of all min occurrences
回答by Fahtima
Just in case someone wishes to use for loop:
以防万一有人希望使用 for 循环:
xy = [50, 2, 34, 6, 4, 3, 1, 5, 2]
t=0
for i in range(len(xy)):
if xy[i]<xy[t]:
t=i
print t

