[英]Insert an element between two adjacent list elements which meet a condition
在python中,在滿足條件的任何兩個元素之間插入元素的干凈方法是什么?
像這樣的電話:
insert_between([1,2,3,4,7,8,9,15,16], 0, lambda x,y: x + 1 != y)
應該產生:
[1,2,3,4,0,7,8,9,0,15,16]
有沒有比迭代和附加到第二個列表更好的方法?
>>> def insert_between(iterable, fill, cond):
... iterable = iter(iterable)
... prev = next(iterable)
... yield prev
... for cur in iterable:
... if cond(prev, cur):
... yield fill
... yield cur
... prev = cur
...
>>>
>>> list(insert_between([1,2,3,4,7,8,9,15,16], 0, lambda x,y: x + 1 != y))
[1, 2, 3, 4, 0, 7, 8, 9, 0, 15, 16]
這非常有效,因為你無論如何都必須在列表中進行一次傳遞,這只能傳遞一次。 請注意,它是一個生成器,因此如果您需要一次所有值,則需要將其強制轉換為列表。
@ katrielalex的版本可能是最有效的方式,無論是在時間還是內存方面。 這是一個返回新列表而不是迭代器的類似版本。
def insert_between(items, insert_item, compare):
result = items[:1]
prev = result[0]
for item in items[1:]:
if not compare(prev, item):
result.append(insert_item)
result.append(item)
prev = item
return result
如果需要在不使用兩個列表的內存的情況下修改列表,則可以執行切片分配。 我有點不喜歡while
這里使用索引和while
循環,但是因為我們正在修改列表,所以在這種情況下它似乎是最簡單的方法。 這將更慢,尤其是對於大型列表,但您還將使用大型列表保存最多的內存。
def insert_between(items, insert_item, compare):
i = 1
while i < len(items):
if not compare(items[i-1], items[i]):
items[i:i] = [insert_item]
i += 1
i += 1
return items
可以使用lambda函數輕松完成並減少
l=[1, 2, 3, 4, 7, 8, 9, 15, 16]
f = lambda l, i: l+[0,i] if l and l[-1]+1!=i else l+[i]
print reduce(f, l, [])
[1, 2, 3, 4, 0, 7, 8, 9, 0, 15, 16]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.