473,387 Members | 1,374 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

better way to write this function

Hello,

This function does I what I want. But I'm wondering if there is an
easier/better way. To be honest, I don't have a good understanding of
what "pythonic" means yet.

def divide_list(lst, n):
"""Divide a list into a number of lists, each with n items. Extra
items are
ignored, if any."""
cnt = len(lst) / n
rv = [[None for i in range(n)] for i in range(cnt)]
for i in range(cnt):
for j in range(n):
rv[i][j] = lst[i * n + j]
return rv

Thanks!
Nov 26 '07 #1
14 1063
Kelie wrote:
Hello,

This function does I what I want. But I'm wondering if there is an
easier/better way. To be honest, I don't have a good understanding of
what "pythonic" means yet.

def divide_list(lst, n):
"""Divide a list into a number of lists, each with n items. Extra
items are
ignored, if any."""
cnt = len(lst) / n
rv = [[None for i in range(n)] for i in range(cnt)]
for i in range(cnt):
for j in range(n):
rv[i][j] = lst[i * n + j]
return rv
You can use slicing:
>>def chunks(items, n):
.... return [items[start:start+n] for n in range(0, len(items)-n+1, n)]
....
>>for i in range(1,10):
.... print chunks(range(5), i)
....
[[0], [1], [2], [3], [4]]
[[0, 1], [2, 3]]
[[0, 1, 2]]
[[0, 1, 2, 3]]
[[0, 1, 2, 3, 4]]
[]
[]
[]
[]

Or build a generator that works with arbitrary iterables:
>>from itertools import *
def chunks(items, n):
.... items = iter(items)
.... while 1:
.... chunk = list(islice(items, n-1))
.... chunk.append(items.next())
.... yield chunk
....
>>list(chunks(range(5), 2))
[[0, 1], [2, 3]]

Peter
Nov 26 '07 #2
On Nov 26, 9:42 am, Kelie <kf9...@gmail.comwrote:
Hello,

This function does I what I want. But I'm wondering if there is an
easier/better way. To be honest, I don't have a good understanding of
what "pythonic" means yet.

def divide_list(lst, n):
"""Divide a list into a number of lists, each with n items. Extra
items are
ignored, if any."""
cnt = len(lst) / n
rv = [[None for i in range(n)] for i in range(cnt)]
for i in range(cnt):
for j in range(n):
rv[i][j] = lst[i * n + j]
return rv

Thanks!
x = ['1', '2', '3', '4', '5', '6', '7', '8']
def divide_list(lst, n):
rv = []
for i in range(int(round((len(lst)/n),0))):
rv.append(lst[i*n:(i+1)*n])
return rv

tmp = divide_list(x, 3)
tmp
[['1', '2', '3'], ['4', '5', '6']]

One way to do it.
Nov 26 '07 #3
Chris <cw****@gmail.comwrites:
for i in range(int(round((len(lst)/n),0))): ...
Ugh!!! Not even correct (under future division), besides being ugly.
I think you mean:

for i in xrange(len(lst) // n): ...

Really though, this grouping function gets reimplemented so often that
it should be built into the stdlib, maybe in itertools.
Nov 26 '07 #4
On Nov 26, 10:51 am, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
Chris <cwi...@gmail.comwrites:
for i in range(int(round((len(lst)/n),0))): ...

Ugh!!! Not even correct (under future division), besides being ugly.
I think you mean:

for i in xrange(len(lst) // n): ...

Really though, this grouping function gets reimplemented so often that
it should be built into the stdlib, maybe in itertools.
Beauty is in the eye of the beholder, but true... Looks crap :p
Nov 26 '07 #5
Kelie <kf****@gmail.comwrites:
Hello,

This function does I what I want. But I'm wondering if there is an
easier/better way. To be honest, I don't have a good understanding of
what "pythonic" means yet.

def divide_list(lst, n):
"""Divide a list into a number of lists, each with n items. Extra
items are
ignored, if any."""
cnt = len(lst) / n
rv = [[None for i in range(n)] for i in range(cnt)]
for i in range(cnt):
for j in range(n):
rv[i][j] = lst[i * n + j]
return rv

Thanks!
See the last recipe from:
http://docs.python.org/lib/itertools-recipes.html. It's not doing
quite the same thing, but gives an illustration of one way to approach
this sort of thing.
Nov 26 '07 #6
On Nov 25, 10:51 pm, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
Really though, this grouping function gets reimplemented so often that
it should be built into the stdlib, maybe in itertools.
thanks Paul.
itertools? that was actually the first module i checked.
Nov 26 '07 #7
On Nov 25, 11:24 pm, Paul Rudin <paul.nos...@rudin.co.ukwrote:
See the last recipe from:http://docs.python.org/lib/itertools-recipes.html. It's not doing
quite the same thing, but gives an illustration of one way to approach
this sort of thing.
Thanks for the link!
Nov 26 '07 #8
On Nov 26, 2007 3:24 AM, Paul Rudin <pa*********@rudin.co.ukwrote:
Kelie <kf****@gmail.comwrites:
Hello,

This function does I what I want. But I'm wondering if there is an
easier/better way. To be honest, I don't have a good understanding of
what "pythonic" means yet.

def divide_list(lst, n):
"""Divide a list into a number of lists, each with n items. Extra
items are
ignored, if any."""
cnt = len(lst) / n
rv = [[None for i in range(n)] for i in range(cnt)]
for i in range(cnt):
for j in range(n):
rv[i][j] = lst[i * n + j]
return rv

Thanks!

See the last recipe from:
http://docs.python.org/lib/itertools-recipes.html. It's not doing
quite the same thing, but gives an illustration of one way to approach
this sort of thing.

--
http://mail.python.org/mailman/listinfo/python-list
The one in the sample consumes the entire sequence up front, too. It's
trivial to write a fully generator based one (and only slightly more
work to implement an iterator that doesn't rely on generators, if you
want to avoid the slight performance hit), but there's a few subtle
issues and I too think that we really should have a good one ready for
use in itertools. Maybe I should write a patch.
Nov 26 '07 #9
On Nov 26, 1:42 am, Kelie <kf9...@gmail.comwrote:
Hello,

This function does I what I want. But I'm wondering if there is an
easier/better way. To be honest, I don't have a good understanding of
what "pythonic" means yet.

def divide_list(lst, n):
"""Divide a list into a number of lists, each with n items. Extra
items are
ignored, if any."""
cnt = len(lst) / n
rv = [[None for i in range(n)] for i in range(cnt)]
for i in range(cnt):
for j in range(n):
rv[i][j] = lst[i * n + j]
return rv

Thanks!
>>lst = list("ABCDE")
for j in range(1,6):
.... print j,':',[lst[i:i+j] for i in xrange(0,len(lst),j)]
....
1 : [['A'], ['B'], ['C'], ['D'], ['E']]
2 : [['A', 'B'], ['C', 'D'], ['E']]
3 : [['A', 'B', 'C'], ['D', 'E']]
4 : [['A', 'B', 'C', 'D'], ['E']]
5 : [['A', 'B', 'C', 'D', 'E']]

Or if you want to discard the uneven leftovers:
>>for j in range(1,6):
.... print j,':',[lst[i:i+j] for i in xrange(0,len(lst),j) if i
+j<=len(lst)]
....
1 : [['A'], ['B'], ['C'], ['D'], ['E']]
2 : [['A', 'B'], ['C', 'D']]
3 : [['A', 'B', 'C']]
4 : [['A', 'B', 'C', 'D']]
5 : [['A', 'B', 'C', 'D', 'E']]

Or define a lambda:
>>chunksWithLeftovers = lambda lst,n: [lst[i:i+n] for i in xrange(0,len(lst),n)]
chunksWithoutLeftovers = lambda lst,n: [lst[i:i+n] for i in xrange(0,len(lst),n) if i+n<=len(lst)]
chunksWithLeftovers(lst,2)
[['A', 'B'], ['C', 'D'], ['E']]
>>chunksWithoutLeftovers(lst,2)
[['A', 'B'], ['C', 'D']]
-- Paul
Nov 26 '07 #10
On Nov 26, 7:42 am, Kelie <kf9...@gmail.comwrote:
Hello,

This function does I what I want. But I'm wondering if there is an
easier/better way. To be honest, I don't have a good understanding of
what "pythonic" means yet.

def divide_list(lst, n):
"""Divide a list into a number of lists, each with n items. Extra
items are
ignored, if any."""
cnt = len(lst) / n
rv = [[None for i in range(n)] for i in range(cnt)]
for i in range(cnt):
for j in range(n):
rv[i][j] = lst[i * n + j]
return rv

Thanks!
Here's a terrible way to do it:

def divide_list(lst, n):
return zip(*[lst[i::n] for i in range(n)])

[It produces a list of tuples rather than a list of lists, but it
usually won't matter].

--
Paul Hankin
Nov 26 '07 #11
Peter Otten wrote:
>>>def chunks(items, n):
... return [items[start:start+n] for n in range(0, len(items)-n+1, n)]
Ouch, this should be

def chunks(items, n):
return [items[start:start+n] for start in range(0, len(items)-n+1, n)]

Peter
Nov 26 '07 #12
On Nov 26, 8:19 am, Peter Otten <__pete...@web.dewrote:
[...]
>
Or build a generator that works with arbitrary iterables:
>from itertools import *
def chunks(items, n):

... items = iter(items)
... while 1:
... chunk = list(islice(items, n-1))
... chunk.append(items.next())
... yield chunk
...>>list(chunks(range(5), 2))

[[0, 1], [2, 3]]

Peter
I was about to send this before I saw your post :)
Well here it is anyway...
Using the fact that StopIteration exceptions fall through list
comprehensions (as opposed to islices):

def chunks(iterable, size):
next = iter(iterable).next
while True:
yield [next() for i in xrange(size)]

--
Arnaud

Nov 26 '07 #13
Peter Otten wrote:
Kelie wrote:
>Hello,

This function does I what I want. But I'm wondering if there is an
easier/better way. To be honest, I don't have a good understanding of
what "pythonic" means yet.

def divide_list(lst, n):
"""Divide a list into a number of lists, each with n items. Extra
items are
ignored, if any."""
cnt = len(lst) / n
rv = [[None for i in range(n)] for i in range(cnt)]
for i in range(cnt):
for j in range(n):
rv[i][j] = lst[i * n + j]
return rv

You can use slicing:
>>>def chunks(items, n):
... return [items[start:start+n] for n in range(0, len(items)-n+1, n)]
...
>>>for i in range(1,10):
... print chunks(range(5), i)
...
[[0], [1], [2], [3], [4]]
[[0, 1], [2, 3]]
[[0, 1, 2]]
[[0, 1, 2, 3]]
[[0, 1, 2, 3, 4]]
[]
[]
[]
[]

This won't work(e.g. you don't define "start", you change the value of n
through the loop). I guess you meant :

def chunks(items, n) :
return [items[i:i+n] for i in range(0, len(items)-n+1, n)]

Nov 27 '07 #14
Ricardo Aráoz wrote:
Peter Otten wrote:
>You can use slicing:
>>>>def chunks(items, n):
... return [items[start:start+n] for n in range(0, len(items)-n+1, n)]
...
>>>>for i in range(1,10):
... print chunks(range(5), i)
...
[[0], [1], [2], [3], [4]]
[[0, 1], [2, 3]]
[[0, 1, 2]]
[[0, 1, 2, 3]]
[[0, 1, 2, 3, 4]]
[]
[]
[]
[]


This won't work(e.g. you don't define "start", you change the value of n
through the loop). I guess you meant :

def chunks(items, n) :
return [items[i:i+n] for i in range(0, len(items)-n+1, n)]
Indeed; I'm still wondering how I managed to copy'n'paste the version with
the typo together with the demo of the correct one.

Peter
Nov 27 '07 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Dan | last post by:
I have seen differing ways to pass values to a class: $db=new mysqlclass('localhost','user','passwd','database'); ..... OR $db=new mysqlclass() $db->host='localhost'; $db->user='user';...
9
by: DPfan | last post by:
When Stroustrup talking about C++ as a better C, he mentioned two points: 1. Inline functions in C++ are better than macros in C. 2. Easier pass-by-reference (and the avoidance of the familiar...
5
by: Hugo Elias | last post by:
Hi all, I have an idea for a better IDE. Though I don't have the skills required to write such a thing, if anyone's looking for a killer app, maybe this is it. If I'm typing at a rate of 10...
8
by: brian.digipimp | last post by:
I turned this in for my programming fundamentals class for our second exam. I am a c++ newb, this is my first class I've taken. I got a good grade on this project I'm just wondering if there is a...
85
by: masood.iqbal | last post by:
I know that this topic may inflame the "C language Taleban", but is there any prospect of some of the neat features of C++ getting incorporated in C? No I am not talking out the OO stuff. I am...
3
by: Paul D. Fox | last post by:
I have this code snippet below where I'm loading all the labels based upon the retrieved record from the DataReader. Unfortunatley, some of the values are null, so I can't explicitly set the...
23
by: JoeC | last post by:
I am a self taught programmer and I have figured out most syntax but desigining my programs is a challenge. I realize that there are many ways to design a program but what are some good rules to...
22
by: JoeC | last post by:
I am working on another game project and it is comming along. It is an improvment over a previous version I wrote. I am trying to write better programs and often wonder how to get better at...
45
by: madhawi | last post by:
Is it better to use a macro or a function?
43
Death Slaught
by: Death Slaught | last post by:
I have made a music player in a pop up with JavaScript. It uses frames to write the object into an unseen page. Here's an example of the page the user first sees. <!DOCTYPE html PUBLIC...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.