Olası Çoğalt:
How do you split a list into evenly sized chunks in Python?Python öğelerini n öğelerine göre gruplama?
Bir liste l boyut n elemanlı gruplarını almak istiyorum:
yani:
[1,2,3,4,5,6,7,8,9] -> [[1,2,3], [4,5,6],[7,8,9]] where n is 3
Olası Çoğalt:
How do you split a list into evenly sized chunks in Python?Python öğelerini n öğelerine göre gruplama?
Bir liste l boyut n elemanlı gruplarını almak istiyorum:
yani:
[1,2,3,4,5,6,7,8,9] -> [[1,2,3], [4,5,6],[7,8,9]] where n is 3
bakın itertools belgelerinin altındaki örnekler: http://docs.python.org/library/itertools.html?highlight=itertools#module-itertools
"Gruplayıcı" yöntemini veya bunun gibi bir şey istiyorsunuz.
Eh, kaba kuvvet cevabı şudur: bir dolgu değeri istiyorsanız
>>> theList = range(10)
>>> N = 3
>>> subList = [theList[n:n+N] for n in range(0, len(theList), N)]
>>> subList
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
, bunu yapabilirsiniz: N
(sizin durumunuzda 3) grup boyutu
subList = [theList[n:n+N] for n in range(0, len(theList), N)]
sağ liste anlama öncesi:
tempList = theList + [fill] * N
subList = [tempList[n:n+N] for n in range(0, len(theList), N)]
Örnek:
>>> fill = 99
>>> tempList = theList + [fill] * N
>>> subList = [tempList[n:n+N] for n in range(0, len(theList), N)]
>>> subList
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 99, 99]]
Sen itertools dokümantasyon sayfasından recipes gelen orfoz kullanabilirsiniz:
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
Bence bunu yapmanın en iyi yolu budur. Ancak, daha yararlı bir cevap burada bağlantı kuracaktır: http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks/434411# 434411, çünkü bunun neden işe yaradığına dair bir tartışma var. – phooji
Nasıl yaklaşık
a = range(1,10)
n = 3
out = [a[k::k+n] for k in range(0,len(a),n)]
Bunu test ettiniz mi? Bence [[1, 4, 7], [4], [7]] 'istenilen çıktı. –
'['] işlevindeki '' 'ekstraını kaldırın. Benim ilk bölümümle aynı cevap. –
answer = [L[3*i:(3*i)+3] for i in range((len(L)/3) +1)]
if not answer[-1]:
answer = answer[:-1]
Yinelenen: http://stackoverflow.com/questions/312443/How-do-you-split-a-list-içine-eşit-büyüklükte-parçaları-python – phooji