Say I have 2 lists
a = [1, 2, 3, 4, 7, 1]
b = [1, 2, 4, 5, 7, 1]
I want it to make a third list with only the elements that are equal in the same index in each list, in this case
c = [1, 2, 7, 1]
Is there a simple way to do this?
simplest method would probably just be doing a list comprehension:
c = [x for x,y in zip(a,b) if x == y]
for the sake of a different approach and just out of interest..could also do it this way:
from itertools import compress
mask = [x==y for x,y in zip(a,b)]
c = list(compress(a,mask))
or if numpy is an option (good for larger lists):
import numpy as np
a,b = np.array(a), np.array(b)
c = a[np.equal(a,b)].tolist()
all ways give:
[1, 2, 7, 1]
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다