이 기사에서는 n개의 배열에서 공통 요소를 찾기 위한 Python의 iintersection_update()에 대해 알아봅니다.
문제는 목록이 포함된 배열이 주어지고 주어진 배열에서 모든 공통 요소를 찾을 수 있다는 것입니다.
알고리즘
1.Initializingres with the first list inside the array 2.Iterating through the array containing lists 3.Updating the res list by applying intersection_update() function to check the common elements. 4.Finally returning the list and display the output by the help of the print statement.
이제 구현을 살펴보겠습니다.
예시
def commonEle(arr):
# initialize res with set(arr[0])
res = set(arr[0])
# new value will get updated each time function is executed
for curr in arr[1:]: # slicing
res.intersection_update(curr)
return list(res)
# Driver code
if __name__ == "__main__":
nest_list=[['t','u','o','r','i','a','l'], ['p','o','i','n','t'], ['t','u','o','r','i','a','l'], ['p','y','t','h','o','n']]
out = commonEle(nest_list)
if len(out) > 0:
print (out)
else:
print ('No Common Elements')
출력
['o', 't']
결론
이 기사에서는 n개의 배열에서 공통 요소를 찾기 위한 Python의 iintersection_update() 및 구현에 대해 배웠습니다.