Is there a way to check if there are two items, in the same place, in two lists in python? For example I would want to be able to get this result
a=[1,2,3,4]
b=[4,1,3,2]
I want a way to get the result "3" out of this but I want it to also be able to check all the items in the list, not just stop after it has found the first one.
答案 0 :(得分:1)
You can try this:
a=[1,2,3,4]
b=[4,1,3,2]
same_place = [i for i, c in zip(a, b) if i == c]
This will give you a list of all values that occur in the same place in the two lists.
答案 1 :(得分:1)
a = [1, 2, 3, 4]
b = [4, 1, 3, 2]
for index, data in enumerate(zip(a, b)):
if data[0] == data[1]:
print('The same at index: {0}, value {1}'.format(index, data[0]))
答案 2 :(得分:0)
my python is a little rusty, so my syntax might be a little off.
effectively what you would do is this,
create a loop that compares the current element of each array to each other, then increment the index by one, and compare the index to the length of the array.
i=0;
a=[1,2,3,4];
b=[4,3,2,1];
while(i>= len(a) -1 && i>= len(b)-1){
if(a[i] == b[i]){
print(a[i]);
}
i++
what this will do is, set an index variable (i) to 0, and compare it to the length of array A and B using the length of the arrays. (len(a) or len(b)) the while loop will only run while the arrays are greater than, or equal to i so if you have an array that is 4 items long, and an array that is 80 items long, it will only loop the number of times of the shorter array's length, and therefore not create an index out of bounds error.
the len()-1 part is due to arrays having zero-based indices and the len() function providing a total number of indexes (including index[0]). for example, array a[] has indices 0, 1, 2, and 3, but has a len() of 4. if you were to loop until i = 4, it would check for a[4] and index-out-of-bounds error.
it then prints the number (if found) to screen, you could even just print out i as well to print out the matching number AND the index it is in.
note; this is unfinished code and will do absolutely nothing if no match is found.
i hope this helps :)