Computer >> Máy Tính >  >> Lập trình >> Python

Traffic_update () trong Python để tìm các phần tử phổ biến trong n mảng

Trong bài viết này, chúng ta sẽ tìm hiểu về iintersection_update () trong Python để tìm ra các phần tử phổ biến trong n mảng.

Bài toán đặt ra là chúng ta được cho một mảng chứa danh sách, hãy tìm tất cả các phần tử chung trong mảng đã cho?

Thuật toán

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.

Bây giờ chúng ta hãy xem việc triển khai nó

Ví dụ

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')


Đầu ra

['o', 't']

Kết luận

Trong bài viết này, chúng ta đã tìm hiểu về iintersection_update () trong Python để tìm các phần tử phổ biến trong n mảng và cách triển khai của nó.