我有一個簡單的程式,我想根據它們是否與主串列中的下一個元素匹配來在追加串列中追加元素,即
'''
-- Append the first element in the append list as it has no previous element
-- After that check if the second element is same as first element
-- if same: Do nothing , if different : Append to the append list
-- The append list will be populated with all the values which don't match their previous values
'''
main_list = ['Apple', 'Apple', 'Apple', 'Apple',
'bat', 'bat', 'bat1', 'bat', 'cat', 'cat', 'cat',
'cat1', 'cat', 'cat', 'Apple', 'Apple', 'Apple',
'Apple']
append_list = ['']
previous_item = []
previous_item_2 = ['']
for item in main_list:
previous_item.append(item)
if previous_item[0] != previous_item_2[0]:
append_list.append(item)
previous_item_2 = []
previous_item_2.append(item)
else :
pass
print(append_list)
使用當前代碼,附加串列只會填充“”和“Apple”
uj5u.com熱心網友回復:
看看輸出
for prev_item, item in zip(main_list, main_list[1:]):
print(prev_item, item)
看看你能不能從那里解決
uj5u.com熱心網友回復:
為 main_list 中的每個專案跟蹤 append_list 中的最后一個元素
main_list = ['Apple', 'Apple', 'Apple', 'Apple',
'bat', 'bat', 'bat1', 'bat', 'cat', 'cat', 'cat',
'cat1', 'cat', 'cat', 'Apple', 'Apple', 'Apple',
'Apple']
append_list= list()
for item in main_list:
l = len(append_list)
if l == 0 or append_list[l-1] != item:
append_list.append(item)
print(append_list)
# output
['Apple', 'bat', 'bat1', 'bat', 'cat', 'cat1', 'cat', 'Apple']
uj5u.com熱心網友回復:
main_list = ['', 'Apple', 'Apple', 'Apple', 'Apple', 'bat', 'bat',
'bat1', 'bat', 'cat', 'cat', 'cat', 'cat1', 'cat', 'cat']
append_list = []
for prev_item, item in zip(main_list, main_list[1:]):
if prev_item != item:
append_list.append(item)
print(prev_item, item)
print(append_list)
uj5u.com熱心網友回復:
res = [None]
lst = ['Apple', 'Apple', 'Apple', 'Apple',
'bat', 'bat', 'bat1', 'bat', 'cat', 'cat', 'cat',
'cat1', 'cat', 'cat', 'Apple', 'Apple', 'Apple',
'Apple']
for word in lst:
if res[-1] != word:
res.append(word)
print(res[1:])
給
['Apple', 'bat', 'bat1', 'bat', 'cat', 'cat1', 'cat', 'Apple']
uj5u.com熱心網友回復:
我發現這特別好用:
append_list = [item for i, item in enumerate(main_list) if main_list[i-1] != item or i == 0]
我對其作業原理的理解是,它遍歷 main_list 中的每個專案,并讓您可以訪問索引,這意味著您可以檢查主串列中的專案,該專案是您當前迭代的元素之前的 1 個元素如果它不等于所述元素或索引為0(它是串列的第一個元素),則添加“item”eitehr
編輯:如果你想在一個回圈中添加到主串列中
for item in ExampleList:
main_list.append(item)
我想你也可以將它添加到同一個回圈中
if item != append_list[-1]: #checks if the item is the same as the last entry to the append list
append_list.append(item) #adds it to the append list
這是我可以從您對您要添加的內容的描述中給出的最佳回應,但是如果這不能達到您想要的效果,請提供一些說明或示例,我可以嘗試為您提供更多幫助
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/490555.html
標籤:Python python-3.x 列表 循环
