Xem thảo luận
Cải thiện bài viết
Lưu bài viết
Xem thảo luận
Cải thiện bài viết
Lưu bài viết
Đọc
Bàn luận
Việc chia tách danh sách là tiện ích khá phổ biến hiện nay và có thể có nhiều ứng dụng và trường hợp sử dụng giống nhau. Cùng với những điều này luôn luôn đến các biến thể. Một biến thể như vậy có thể được chia danh sách theo giá trị cụ thể. Hãy để thảo luận về một cách nhất định trong đó phân chia danh sách có thể được thực hiện.
Phương pháp: Sử dụng danh sách hiểu + zip() + slicing + enumerate()
Vấn đề này có thể được giải quyết trong hai phần, trong phần đầu tiên, chúng tôi nhận được danh sách chỉ mục bằng cách phân chia phải được thực hiện bằng cách sử dụng hàm liệt kê. Và sau đó chúng ta có thể tham gia các giá trị theo các chỉ số bằng cách sử dụng ZIP và Danh sách cắt.
test_list =
['Geeks'] ['is a', 'portal', 'for Geeks']5['Geeks'] ['is a', 'portal', 'for Geeks']6['Geeks'] ['is a', 'portal', 'for Geeks']7 ['Geeks'] ['is a', 'portal', 'for Geeks']8 ['Geeks'] ['is a', 'portal', 'for Geeks']9zip() + slicing + enumerate()0
zip() + slicing + enumerate()1= zip() + slicing + enumerate()3zip() + slicing + enumerate()4
zip() + slicing + enumerate()5= zip() + slicing + enumerate()7['Geeks'] ['is a', 'portal', 'for Geeks']8 1 test_list 0 test_list 1test_list 2
test_list 3test_list 4___
=2= =4test_list 0 =6test_list 2
Các
=8[7test_list 6
The original list : [1, 4, 5, 6, 4, 5, 6, 5, 4] The list after splitting by a value : [[1, 4, 5], [6, 4, 5], [6, 5], [4]]Xem thảo luận
Cải thiện bài viết
Lưu bài viết
Xem thảo luận
Cải thiện bài viết
Lưu bài viết
Đọc
The approach is very simple.
Split the first half of list by given value, and second half from the same value. There are multiple variations possible from this operation based on the requirement, like dropping the first/some element(s) in second half after the split value etc. Let’s see the different ways we can do this task.
Phương pháp số 1: Sử dụng List Index & NBSP;
Python3
, 3 = [, 6, __888____840, __92
‘
Các
['Geeks'] ['is a', 'portal', 'for Geeks']5['Geeks'] ['is a', 'portal', 'for Geeks']16
['Geeks'] ['is a', 'portal', 'for Geeks']5['Geeks'] ['is a', 'portal', 'for Geeks']18
Output:
['Geeks'] ['is a', 'portal', 'for Geeks']Phương pháp số 2: Sử dụng Dropwhile và Set & NBSP;
Python3
['Geeks'] ['is a', 'portal', 'for Geeks']19 ['Geeks'] ['is a', 'portal', 'for Geeks']20['Geeks'] ['is a', 'portal', 'for Geeks']21 ['Geeks'] ['is a', 'portal', 'for Geeks']22
Các
['Geeks'] ['is a', 'portal', 'for Geeks']04= , 3['Geeks'] ['is a', 'portal', 'for Geeks']39['Geeks'] ['is a', 'portal', 'for Geeks']40 ['Geeks'] ['is a', 'portal', 'for Geeks']41=
‘
['Geeks'] ['is a', 'portal', 'for Geeks']54, 8['Geeks'] ['is a', 'portal', 'for Geeks']11
46= , 3['Geeks'] ['is a', 'portal', 'for Geeks']16
['Geeks'] ['is a', 'portal', 'for Geeks']5['Geeks'] ['is a', 'portal', 'for Geeks']16
['Geeks'] ['is a', 'portal', 'for Geeks']5['Geeks'] ['is a', 'portal', 'for Geeks']18
Output:
['Geeks'] ['is a', 'portal', 'for Geeks']