[英]python: How to compare elements within one list
I'm trying to find the minimum value in a list using a for loop but I'm not getting the right answer.我正在尝试使用 for 循环在列表中找到最小值,但我没有得到正确的答案。
This is what I am doing:这就是我正在做的:
xs=[5,3,2,5,6,1,0,5]
for i in xs:
if xs[i]< xs[i+1]:
print(i)
edit: sorry i should've said this earlier but I'm not allowed to use the min function!编辑:对不起,我应该早点说这个,但我不允许使用 min 函数!
Use the min
method:使用min
方法:
xs=[5,3,2,5,6,1,0,5]
print min(xs)
This outputs:这输出:
0
If you want to use for
loop , then use following method如果要使用for
循环,请使用以下方法
xs=[5,3,2,5,6,1,0,5]
minimum = xs[0];
for i in xs:
if i < minimum:
minimum = i ;
print(minimum)
Without loop , you can use the min
method没有循环,您可以使用min
方法
minimum = min(xs)
print(minimum)
Why use a for loop ?为什么要使用 for 循环?
Just use:只需使用:
xs=[5,3,2,5,6,1,0,5]
print min(xs)
I assume you intend to find successive elements that are in lesser to greater order.我假设您打算查找顺序从小到大的连续元素。 If this is the case then this should work如果是这种情况,那么这应该有效
for i in xrange(len(xs)-1):
if xs[i]< xs[i+1]:
print(i)
>>> xs=[5,3,2,5,6,1,0,5]
>>> print min(xs)
#Prints 0
您可以使用内置函数reduce()
在没有 for 循环和min()
情况下执行此操作:
minimum = reduce(lambda x, y: x if x < y else y, xs)
You can try this你可以试试这个
xs=[5,3,2,5,6,1,0,5]
minvalue=xs[0] #Assuming first value in xs as minimum value
for i in range(0,len(xs)):
if xs[i]< minvalue: #If xs[i] is less than minimum value then
minvalue=xs[i] #minmumvalue=xs[i]
print(minvalue) #print minvalue outside for loop
Output: 0输出:0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.