开发者

How to return every 5 items from a list in python?

I am using python and would like to return every 5 items from a list and put them into csv format.

Also, if there are less than 5 items in the iteration then I need to zero fill to get 5 items.

I am using a fairly old version of python 2.1 wh开发者_Go百科ich can not be changed so i do not have access to 'iter'.

Thanks.


Including the padding, this might work. (There are list comprehensions in 2.1, right? Just looked it up -- they were added in 2.0.)

a = the_list
a += [0] * (-len(a) % 5)
result = [a[i:i + 5] for i in range(0, len(a), 5)]

In less ancient Python, I would replace the last line by

result = zip(*[iter(a)] * 5)


Is this what you want?

rows = []
while a_list:
    rows.append(a_list[:5])
    a_list = a_list[5:]


this works in python 2.4. Not sure if everything is possible in 2.1:

def to_csv(l, columns=5):
  l = l + [0]*((columns-1) - (len(l)-1)%columns)
  ll = [ l[i:len(l):columns] for i in range(columns) ]
  for row in zip(*ll): print ', '.join( str(xi) for xi in row )


Code:

# 1. Doesn't mutate the input list
# 2. Doesn't waste memory on a temporary list of rows
# 3. Handles the CSV requirement, including quoting strings properly

float_type = type(0.0)

def csv_escape(pyrow, quotechar='"', delimiter=',', terminator='\r\n'):
    outlist = []
    for obj in pyrow:
        if isinstance(obj, float_type):
            s = repr(obj) # Get full precision. BTW the csv module doesn't do this :-(
        else:
            s = str(obj) # This may need further elaboration
        if quotechar in s:
            x = quotechar + s.replace(quotechar, quotechar+quotechar) + quotechar
        elif delimiter in s or '\r' in s or '\n' in s:
            x = quotechar + s + quotechar
        else:
            x = s
        outlist.append(x)
    return delimiter.join(outlist) + terminator

def emit_list_in_slices(alist, file_handle,
                        slice_size=5, pad_value=0, slice_formatter=csv_escape):
    for i in xrange(0, len(alist), slice_size):
        row = alist[i:i+slice_size]
        n = len(row)
        if n and n != slice_size:
            row.extend([pad_value] * (slice_size - n))
        file_handle.write(csv_escape(row))

if __name__ == "__main__":
    test_list = range(9) + [1.0 / 11.0, 'He said "Hello"', 'foo,bar', 'zot']
    f = open('demo.csv', 'wb') #### Note: binary
    emit_list_in_slices(test_list, f)
    f.close()

Running with this Python: Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32:

C:\junk>\python21\python csvslice21.py

C:\junk>more demo.csv
0,1,2,3,4
5,6,7,8,0.090909090909090912
"He said ""Hello""","foo,bar",zot,0,0


I think this should work in Python 2.1 (I don't have it installed here to test). We leave the input array unmodified.

# create input
a = list(range(20, 43))

values = [a[i:i+5] for i in range(0, len(a), 5)]
values[-1] += (-len(values[-1]) % 5) * [0]
csv = [','.join([str(v) for v in vs]) for vs in values]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜