New in Python Vectors Need Advice
本问题已经有最佳答案,请猛点这里访问。
我两天内就要考试了,老师给我举了个例子,但我对python不太熟悉,对此我有点束手无策。
这是问题陈述:
Write an algorithm which will get the parameters two array of integers x[1..n] if y[1..n] which returns number of common elements in the two arrays.
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 | def apartine(a,e): e=1 gasit=False n=len(a) i=0 while i<=n and gasit==False: if a[i]==e: gasit=True else: i=i+1 return gasit def intersectie(a,b,c): e=0 k=len(c) m=len(b) for i in range(1,m): if apartine(a,e)==True: k=k+1 c.append(b[i]) print(c) return c a=[1,3,5,7] b=[2,3,4,6] c=[] print intersectie(a,b,c) |
我受不了了。
我需要一些帮助来找出我做错了什么。
简单的列表理解可以做到这一点:
1 | c=[i for i in a if i in b] |
如果您很难理解列表中的含义,那么下面的内容基本上与for循环相同:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | def intersect(a, b): """Return a list of all elements common to a & b """ intersection = [] for element in a: if element in b and element not in intersection: intersection.append(element) return intersection if __name__ == '__main__': test_pairs = ( ([1, 3, 5, 7], [2, 3, 4, 6]), ([3], [1, 2, 3]), ([1, 2, 3], [3]), ([3, 3, 3], [3]), ([3], [3, 3, 3]), ([1, 2, 3], [4, 5, 6]) ) for a, b in test_pairs: print"Intersection of %s and %s is %s" % (a, b, intersect(a,b)) |
输出是:
1 2 3 4 5 6 | Intersection of [1, 3, 5, 7] and [2, 3, 4, 6] is [3] Intersection of [3] and [1, 2, 3] is [3] Intersection of [1, 2, 3] and [3] is [3] Intersection of [3, 3, 3] and [3] is [3] Intersection of [3] and [3, 3, 3] is [3] Intersection of [1, 2, 3] and [4, 5, 6] is [] |
方法是从一个列表中获取每个元素(不管是哪个列表),然后查看它是否存在于另一个列表中。将这些元素收集到第三个列表中,这就是您的结果。如您所见,这些副本由
如果列表中的位置无关紧要,您可以用一个简单的理解列表获得公共元素。
1 | commons = [x for x in a if x in b] |
如果位置重要,可以使用索引
1 | commons = [a[i] for i in range(len(a)) if a[i] == b[i]] |
公共元素的数目就是这个列表的长度。
1 | print(len(commmons)) |
你在
你想打电话给
你没有使用
用Python实现整个过程的一个非常简单的方法是:
1 | c = list(set(a) & set(b)) |
但我想这不是你想要的。