Comparing Python lists
I have several long lists in python 开发者_如何转开发and have compare them and find the lists that are equal to each other except the last elements in the them. Which is the fastest way?
a[:-1]
is shorthand for "all the elements of a
but the last one." If you need more than 1 element to be excluded, change the 1 to the number you need.
a[:-1] == b[:-1]
will compare a
and b
without their final elements.
See this for more information on slicing.
Use something like if list1[:-1] == list2[:-1]
.
To compare two lists, I think something like this would avoid copying any part of your lists, and stops as soon as a mismatch is found:
len(a)==len(b) and all(a[i] == b[i] for i in range(len(a)-1))
To find all matches in an arbitrary set of lists, I think you'd need to compare each pair of lists -- or at least, each pair which you haven't checked some equivalent version of (e.g., if A=B and B=C, you don't need to check A=C). I don't know offhand of an algorithm that makes this simple.
Alternatively, if the lists are outrageously long and you want to avoid traversing them, you could maybe compute a checksum of the first N-1 elements of each, and then just compare the checksums.
# choose n to be whatever "last few elements" you want
n = 5
if list1[:-n] == list2[:-n]:
print("The lists are the same")
Using the variable n
lets you exclude any number of last "elements" from the lists.
精彩评论