Python Comparing Lists
我想比较两个列表,并想知道一个元素是否对应于另一个元素。
例子:"a"应对应于"b"在这里,它将返回真。
1 2 | list1 = [a,b,c,d] list2 = [b,a,d,c] |
"a"和"b"相互对应(它们在列表中共享相同的位置)。如果函数对应,如何使其返回true?
1 2 | list1 = [a,b,c,d] list2 = [c,d,a,b] |
号
这将返回false。
我会这样做:
1 2 3 4 5 | >>> from operator import eq >>> list1 = ['a','b','c','d'] >>> list2 = ['c','d','a','b'] >>> any(map(eq, list1, list2)) False |
。
当然,如果您想要完整的布尔"对应"列表,只需省略
1 2 | >>> map(eq, list1, list2) [False, False, False, False] |
首先,让我们构建一个迭代器,它将给出元素
1 2 | # This is a generator expression: it works like a list, but uses O(1) memory a_indexes = (i for i, x in enumerate(list1) if x == a) |
现在,让我们确保
1 2 | # This returns a boolean b_matches = all(list2[i] == b for i in a_indexes) |
。
编辑:请注意,
以下是我提出的更新版本(满足您的示例用例):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | def correspond(a, b): """Looks at two lists, if they are the same length and the length is even then it looks to make sure that the pairs are swapped (even if they are moved) >>> print correspond([1,2,3,4], [2,1,4,3]) True >>> print correspond([1,2,3,4], [2,1,4,5]) #One value is out of place False >>> print correspond([1,2,3,4], [2,1,3]) #One value list is shorter False >>> print correspond([1,2,3,4], [3,4,1,2]) #values are moved but not swapped False >>> print correspond("ABCD","BADC") True """ if len(a) == len(b) and len(a) % 2 == 0: try: for i in xrange(0,len(a),2): if (1+b.index(a[i])) == b.index(a[i+1]): return False return True except ValueError: return False else: return False if __name__ =="__main__": import doctest doctest.testmod() |
这就是你想要的吗?我假设
1 2 | def corresponding(list1,list2,a,b): return list1.index(a) == list2.index(b) |
1 | list2[::2] == list1[1::2] and list1[::2] == list2[1::2] |
你的问题不清楚,但我认为你想要的是:
1 2 3 4 5 6 7 8 9 10 | first = 'a' second = 'b' list_one = ['a','b','c','d'] list_two = ['b','c','d','e'] if list_one.index(first) == list_two.index(second): print("They correspond") else: print("They don't") |
。
上述操作将忽略重复项(
像这样的东西应该给你想要的:
1 2 3 4 5 6 | import itertools as it def are_related(first, second, a, b): a_indexes = (i for i,x in enumerate(first) if x == a) b_indexes = (i for i,x in enumerate(second) if x == b) return all(a_i == b_i for a_i, b_i in it.izip_longest(a_indexes, b_indexes)) |
。
注意,使用
您可以比较您认为应该对应的值的索引:
1 2 | def in_correspondence(my_list1, my_list2, val1, val2): return my_list1.index(a) == my_list2.index(b) |
号