简体   繁体   English

如何比较列表中的元素

[英]How to compare elements in a list

I'm having some trouble with an algorithm (To find the max and min values), not the algorithm itself but the implementation, let me explain: 我在使用算法时遇到了麻烦(要查找最大值和最小值),而不是算法本身,而是实现,请让我解释一下:

Let's say the list is n = [0,1,1,2,3,5,8,13,-1,99] ; 假设列表为n = [0,1,1,2,3,5,8,13,-1,99] ; len(n) = 10 Then globalMin, globalMax = n[0], n[0] #To skip 1 iteration from the list len(n) = 10然后globalMin, globalMax = n[0], n[0] #从列表中跳过1次迭代

And now what I have to do is compare by 'pairs', so since I already used n[0] I start comparing n[1] and n[2] to find the max and min values between those 2 and then compare it with y global min, max values, then n[3] and n[4] and compare the nm with my global values, then n[5] and n[6] .. until I have to compare n[9] and n[10], as you can see n[10] doesn't exist on my list. 现在,我要做的是按“对”进行比较,因此,由于我已经使用n [0],因此开始比较n [1]和n [2]来找出这2个之间的最大值和最小值,然后将其与y个全局最小值,最大值,然后是n [3]和n [4],然后将nm与我的全局值进行比较,然后是n [5]和n [6] ..,直到我必须比较n [9]和n [ 10],如您所见,我的列表中不存在n [10]。 I thought I could solve this with list slicing using the next code: 我以为可以使用下一个代码通过列表切片解决此问题:

 for i in range(1, len(n), 2):

    if n[i:i+1] > n[i+1:i+2]:
      minl, maxl = n[i+1:i+2], n[i:i+1] # minl = local min; maxl = local max
    else:
      maxl, minl = n[i+1:i+2], n[i:i+1]

But this wont work if my last element is only one (as on the example above) so, as you can guess, If the min or max is the last element on my list it will be ignored. 但是,如果我的最后一个元素只有一个(如上例所示),则将无法工作,因此,您可以猜测,如果min或max是列表中的最后一个元素,它将被忽略。 I have been trying to fix this with index or list slicing but no luck at all, any suggestions? 我一直在尝试通过索引或列表切片来解决此问题,但是一点都不运气,有什么建议吗? I have to do this in a 'Pythonic' way and making sure to make this as simple and short as possible without using imports. 我必须以“ Pythonic”方式执行此操作,并确保在不使用导入的情况下使其尽可能简单和简短。 I have figured the rest of the algorithm which is based on the next image: Image 我想通这是基于对下一个图像算法的其余部分: 图片

You can check the length of list first, if it's of odd length then you can append the last element at the end of the list. 您可以先检查列表的长度,如果它的长度是奇数,则可以在列表末尾附加最后一个元素。 Appending is an O(1) operation, so, it won't affect the time complexity. 追加是O(1)操作,因此不会影响时间复杂度。

You can use a while loop: 您可以使用while循环:

In [78]: lis = [0,1,1,2,3,5,8,13,-1]

In [79]: if len(lis)%2 !=0 :  #if the list is of odd length then append the last item to it
    lis.append(lis[-1])
   ....:     

In [80]: i=0

In [81]: while i<len(lis)-1:
    if lis[i]>lis[i+1]:
        local_max,local_min=lis[i],lis[i+1]
    elif lis[i]<lis[i+1]:    
        local_max,local_min=lis[i+1],lis[i]
    else:
        local_max,local_min=lis[i],lis[i+1]
    print local_min,local_max
    i+=2
   ....:     
0 1
1 2
3 5
8 13
-1 -1

or you can use an iterator: 或者您可以使用迭代器:

In [86]: it=iter(lis)

In [87]: lis = [0,1,1,2,3,5,8,13,-1]

In [88]: if len(lis)%2 !=0 :
    lis.append(lis[-1])
   ....:     

In [89]: it=iter(lis)

In [90]: for _ in xrange(len(lis)/2):
   ....:     a,b=next(it),next(it)
   ....:     if a>b:
   ....:         local_max,local_min=a,b
   ....:     elif a<b:    
   ....:         local_max,local_min=b,a
   ....:     else:    
   ....:         local_max,local_min=a,b
   ....:     print local_min,local_max    
   ....:     
0 1
1 2
3 5
8 13
-1 -1

I would argue this is the most Pythonic implementation of this: 我认为这是最Python化的实现:

from itertools import zip_longest

n = [0, 1, 1, 2, 3, 5, 8, 13, -1, 99]
global_min = global_max = n[0]

groups = [iter(n)] * 2
for a, b in zip_longest(*groups):
    if b is not None:
        if a > b:
            local_min, local_max = b, a
        else:
            local_min, local_max = a, b
    else:
        local_min = local_max = a
    if local_min < global_min:
        global_min = local_min
    if local_max > global_max:
        global_max = local_max

print(global_min, global_max)

We group the items by using itertools.zip_longest() ( itertools.izip_longest() in 2.x) and a list of the same iterator repeated. 我们组通过使用项目itertools.zip_longest() itertools.izip_longest()在2.X),并重复同样的迭代器的列表。 We then loop over this, which gives us the values in pairs. 然后,我们对此进行循环,从而为我们提供成对的值。 We then do a check, if the value is the last one, we assign it as the local_min and local_max , otherwise, we compare the two values and assign as appropriate. 然后,我们做一个检查,如果该值是最后一个,我们其指定为local_minlocal_max ,否则,我们比较两个值,并在适当分配。

We then compare (and potentially update) global_min and global_max . 然后,我们比较(并可能更新) global_minglobal_max

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM