简体   繁体   English

如何在一个循环中比较两个列表的值是否相等?

[英]How can I compare for equality the values of two lists in one loop?

So I want to make this so I can check if another code is working, but I keep getting this error: 所以我想这样做,以便我可以检查另一个代码是否正常工作,但是我一直收到此错误:

'list index out of range'

For the following code: 对于以下代码:

for L1[i] in range(0, len(L1)):
    if L1[i]==L2[i]:
        L1[i]='ok'

What is going wrong? 怎么了?

You probably are looking for something more like this. 您可能正在寻找更多类似这样的东西。 I recommend prevalidating your list lengths are equal so that your loop doesn't fall over. 我建议预先验证您的列表长度是否相等,以免循环失败。

assert len(L1) == len(L2)

for i in range(len(L1)):
    if L1[i] == L2[i]:
        L1[i] = 'ok'

Alternately, if it is acceptable for your lists to be of different lengths, simply take the minimum of the two lengths as your exclusive upper bound. 或者,如果可以接受长度不同的列表,则只需将两个长度中的最小值作为唯一上限。

upper_bound = min(len(L1), len(L2))
for i in range(upper_bound):

How about: 怎么样:

import itertools
zipped_pairs = itertools.izip_longest(L1, L2, fillvalue=object()) # generator of pairs (L1[n],L2[n])
equals_tests = (a == b for a,b in zipped_pairs) # perform equality test on each pair
all_equal = all(equals_tests) # True if all of the equals_tests items are True

Or in one line: 或一行:

all((a == b for a,b in itertools.izip_longest(L1, L2, fillvalue=object()))

Note that this will ultimately return false whenever L1 and L2 are of different lengths. 请注意,只要L1和L2的长度不同,这最终将返回false。 If you want to have something else, alter the equals_tests step to use the test you prefer. 如果您还有其他要求,请更改equals_tests步骤以使用您喜欢的测试。 You may also need to use a different fillvalue parameter for izip_longest . 您可能还需要为izip_longest使用不同的fillvalue参数。

In fact, here's a version which will treat an empty place as equal to anything: 实际上,这是一个将空地方等同于任何事物的版本:

nonce = object()
all(((a == b) or (nonce in (a,b)) for a,b in itertools.izip_longest(L1, L2, fillvalue=nonce))

Assuming this is Python, there are two problems: 假设这是Python,则有两个问题:

  1. You only want to specify i in the beginning of the for -loop. 您只想在for循环的开头指定i
  2. L2 may not have as many items as L1 . L2可能没有L1那样多的项目。

for i in range(0, len(L1)):
    try:
        if L1[i] == L2[i]:
            L1[i] = 'ok'
    except IndexError:
        break

As Frederik points out, you could use enumerate as well: 正如Frederik所指出的,您也可以使用enumerate

for i, l1 in enumerate(L1):
    try:
        if L[i] == L2[i]:
            L1[i] = 'ok'
    except:
        break

In my opinion, the increase in readability of enumerate over range is mostly offset by defining an extra variable ( l1 ) which you never use. 我认为, enumeraterange可读性的提高大部分通过定义一个从未使用过的额外变量( l1 )来抵消。 But it is just my opinion. 但这只是我的意见。


One last option, which may be best, is to use zip to merge the two lists ( zip truncates the longer of the two): 最好的最后一种选择是使用zip合并两个列表( zip截断两个列表中的较长者):

for i, l1, l2 in enumerate( zip(L1, L2) ):
    if l1 == l2:
        L1[i] = 'ok'

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

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