[英]Python/Pandas for loop through a list only working on the last item in the list
[英]How to loop through all but the last item of a list?
我想遍歷一個列表,將每個項目與它后面的項目進行對照。
有沒有一種方法可以遍歷除最后一項以外的所有項,以便在y中使用x? 如果可以的話,我寧願不使用索引就這樣做。
注意
freespace回答了我的實際問題,這就是為什么我接受答案,但是SilentGhost回答了我應該問的問題。
抱歉造成混亂。
for x in y[:-1]
如果y
是發電機,則以上方法將無效。
比較序列項與以下內容的最簡單方法:
for i, j in zip(a, a[1:]):
# compare i (the current) to j (the following)
如果要成對獲取序列中的所有元素,請使用這種方法(成對函數來自itertools模塊中的示例)。
from itertools import tee, izip, chain
def pairwise(seq):
a,b = tee(seq)
b.next()
return izip(a,b)
for current_item, next_item in pairwise(y):
if compare(current_item, next_item):
# do what you have to do
如果需要將最后一個值與某個特殊值進行比較,則將該值鏈接到末尾
for current, next_item in pairwise(chain(y, [None])):
如果您要比較列表中的第n個項目與第n + 1個項目,則也可以使用
>>> for i in range(len(list[:-1])):
... print list[i]>list[i+1]
請注意,那里沒有硬編碼。 除非您另有感覺,否則應該可以。
要在迭代器中將每個項目與下一個項目進行比較而不實例化列表:
import itertools
it = (x for x in range(10))
data1, data2 = itertools.tee(it)
data2.next()
for a, b in itertools.izip(data1, data2):
print a, b
這回答了OP 應該問的問題 ,即遍歷比較連續元素的列表(出色的SilentGhost答案),但對任何組( n-gram )都可以推廣:2、3,... n
:
zip(*(l[start:] for start in range(0, n)))
例子:
l = range(0, 4) # [0, 1, 2, 3]
list(zip(*(l[start:] for start in range(0, 2)))) # == [(0, 1), (1, 2), (2, 3)]
list(zip(*(l[start:] for start in range(0, 3)))) # == [(0, 1, 2), (1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 4)))) # == [(0, 1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 5)))) # == []
說明:
l[start:]
從索引start
生成一個列表/生成器 *list
或*generator
:將所有元素傳遞到封閉函數zip
就像寫成zip(elem1, elem2, ...)
注意:
AFAIK,此代碼盡可能地懶惰。 未經測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.