[英]Making new list of list with some condition of other list
我是python的新手,仍然在為之奮斗。 你們可以幫我嗎?
我有以下列表列表:
sorted_Region: [[J, 0.80, 0.30], [H, 0.80, 0.21], [I, 0.87, 0.19], [G, 0.88, 0.15], [D, 0.96, 0.14], [B, 0.97, 0.14], [A, 1.01, 0.11], [C, 1.05, 0.15], [F, 1.06, 0.04], [E, 1.55, 0.22]]
我想使用條件創建新的列表列表:如果下一個列表的第二個元素值大於或等於當前列表的第二個元素,並且下一個列表的第三個元素值小於當前列表的第三個元素。
我嘗試了這段代碼
Region_frontier = []
for i in sorted_Region:
if i+1[1] >= i[1] and i+1[2] < i[2]:
Region_frontier.append(i)
print Region_frontier
但我收到此錯誤消息。
TypeError: 'int' object has no attribute '__getitem__'
請幫助我。 預先謝謝^^
首先,我假設以前是指要迭代的當前元素。 另外,我想提到的是,您有一個列表列表,而不是一組元組。 由於python具有類似的關鍵字,因此在使用這些單詞時應格外小心。 現在談論你的問題
問題是您要遍歷“ int”而不是列表。 當您i in sorted_Region
執行i in sorted_Region
“ i”是該列表的元素,而不是其迭代器。 因此,您可以執行以下操作
Region_frontier = []
i = 0
while i < len(sorted_Region)-1:
if sorted_Region[i+1][1] >= sorted_Region[i][1] and sorted_Region[i+1][2] < sorted_Region[i][2]:
Region_frontier.append(sorted_Region[i])
print(Region_frontier)
對於i+1[1]
,獲取'int'對象的索引項是錯誤語法。 出於預期目的, sorted_Region
的for循環中沒有索引,因此無法獲得“ previous tuple
”。
要迭代sorted_Region
並與附近的項目進行比較,請嘗試使用元組索引(實際索引i
范圍為0到len(sorted_Region) - 1
):
Region_frontier = []
for i in range(0, len(sorted_Region) - 1):
if sorted_Region[i+1][1] >= sorted_Region[i][1] and sorted_Region[i+1][2] < sorted_Region[i][2]:
Region_frontier.append(i)
print Region_frontier
for index in range(len(sorted_Region)-1):
if sorted_Region[index+1][i] >= sorted_Region[index][1] and sorted_Region[index+1][2]<sorted_Region[index][2]:
Region_frontier.append(i)
print Region_frontier
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.