Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

python - Find min value in array > 0

I am looking to find the lowest positive value in an array and its position in the list. If a value within the list is duplicated, only the FIRST instance is of interest. This is what I have which does what I want but includes 0.

print "Position:", myArray.index(min(myArray))
print "Value:", min(myArray)

for example, as it stands if,

myArray = [4, 8, 0, 1, 5]

then Position: 2, Value: 0

I want it to present position: 3, value: 1

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a generator expression with min. This will set m as the minimum value in a that is greater than 0. It then uses list.index to find the index of the first time this value appears.

a = [4, 8, 0, 1, 5]

m = min(i for i in a if i > 0)

print("Position:", a.index(m))
print("Value:", m)
# Position: 3
# Value: 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...