[英]How to split list of lists based on the repetitivity of the value of the lists?
假設我有一個以坐標格式表示的列表列表:
[['1', '1'],
['2', '2'],
['3', '3'],
['1', '1'],
['5', '5'],
['6', '6'],
['7', '7'],
['5', '5'],
['8', '8'],
['9', '9'],
['10', '10'],
['8', '8']]
我想列表這個列表分成列表3所列出,使得第一列表與該列表開始[1, 1]
和與該列表結束[1, 1]
第2開始與列表[5, 5]
和以列表[5, 5]
等結束
因此,基本上,我想每次遇到與列表初始值相同的值時創建一個新列表。
關於如何實現這種操作的任何想法嗎?
編輯。 我嘗試了一些嘗試,但未獲得預期結果:
poly_pts = []
for pt in tlist:
x = 0
init_pt = tlist[0]
if pt != init_pt:
poly_pts.append(pt)
x += 1
elif pt == init_pt:
poly_pts.append(pt)
init_pt = tlist[x+1]
#
all_lists = []
init_pt = tlist[0]
for pt_i, pt in enumerate(tlist):
if pt == init_pt and pt_i != tlist.index(init_pt):
all_lists.append(tlist[tlist.index(init_pt):pt_i+1])
嘗試這個:
t = [['1', '1'],
['2', '2'],
['3', '3'],
['1', '1'],
['5', '5'],
['6', '6'],
['7', '7'],
['5', '5'],
['8', '8'],
['9', '9'],
['10', '10'],
['8', '8']]
ix = 0
tmp = []
while ix < len(t):
tmp.append(t[ix:t.index(t[ix], ix+1)+1])
ix = t.index(t[ix], ix+1) + 1
>>> tmp
[[['1', '1'], ['2', '2'], ['3', '3'], ['1', '1']], [['5', '5'], ['6', '6'], ['7', '7'], ['5', '5']], [['8', '8'], ['9', '9'], ['10', '10'], ['8', '8']]]
我不檢查任何錯誤,具體取決於您來實現。 我正在使用[].index
,它給出列表中元素的索引,該函數還可以使用第二個參數來指定要從哪個索引中搜索元素。
您可以這樣做:
first = []
all_lists = []
j = 0
for i, item in enumerate(a):
if first == []:
first = a[i]
print(first)
elif first == a[i]:
all_lists.append(a[j:i+1])
j = i + 1
first = []
print(all_lists)
它類似於您的第一次嘗試,但是我使用enumerate()給我一個索引和項目的元組。 訣竅是在找到匹配項后首先重新斷言(如代碼中的init_pt)為空。
list.index()
給出元素在列表中首次出現的位置的索引
temp =[]
while True:
try:
idx = list[1:].index(list[0])
except ValueError:
temp.append(list)
break
if idx == len(list)-2:
temp.append(list)
break
temp.append(list[:idx+2])
list = list[idx+2:]
上面代碼中本質上發生的是
在try
內,我們嘗試獲取列表中除firs元素之外的列表中第一個元素的索引。 如果列表的其余部分沒有元素,則引發ValueError
並結束循環
如果我們獲得元素的索引,那么例如列表中有5個元素,例如list=[1,2,3,4,1]
idx = 3
所以如果idx+2 = len(list)
,那將是循環的結尾,因為在列表的這一部分之后將不留任何元素。
否則,循環將繼續對列表進行切片,直到出現以上兩種情況之一
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.