list-comprehension

how to rewrite this loop in a more efficient way in python

I have a loop of the following type: a = range(10) b = [something] for i in range(len(a)-1): b.append(someFunction(b[-1], a[i], a[i+1])) However the for-loop is killing a lot of performance. I have try to write a windows generator to give me 2 elements everything time but it still require explicit for-loop in the end. Is there a w...

List of Lists in python?

I need a good function to do this in python. def foo(n): # do somthing return list_of_lists >> foo(6) [[1], [2,3], [4,5,6]] >> foot(10) [[1], [2,3], [4,5,6] [7,8,9,10]] NOTE:Seems like my brain has stopped functioning today. ...

Python: List comprehension to assign different values

I'm making a 2D list and I would like to initialize it with a list comprehension. I would like it to do something like this: [[x for i in range(3) if j <= 1: x=1 else x=2] for j in range(3)] so it should return something like: [[1,1,1], [1,1,1], [2,2,2]] How might I go about doing this? Thanks for your help. ...

How can I handle exceptions in a list comprehension in Python?

I have some a list comprehension in Python in which each iteration can throw an exception. For instance, if I have: eggs = (1,3,0,3,2) [1/egg for egg in eggs] I'll get a ZeroDivisionError exception in the 3rd element. How can I handle this exception and continue execution of the list comprehension? The only way I can think of is...

Comprehensions in Python and Javascript are only very basic?

Looking at comprehensions in Python and Javascript, so far I can't see some of the main features that I consider most powerful in comprehensions in languages like Haskell. Do they allow things like multiple generators? Or are they just a basic map-filter form? If they don't allow multiple generators, I find them quite disappointing ...

Iterating through a list in Python

I am trying to iterate through a list and take each part of the list, encode it and join the result up when it is all done. As an example, I have a string which produces a list with each element being 16 characters in length. message = (u'sixteen-letters.sixteen-letters.sixteen-letters.sixteen-letters.') result = split16(message, 16) m...

Nesting generator expressions in the argument list for a python function call

I like to use the following idiom for combining lists together, sometimes: >>> list(itertools.chain(*[[(e, n) for e in l] for n, l in (('a', [1,2]),('b',[3,4]))])) [(1, 'a'), (2, 'a'), (3, 'b'), (4, 'b')] (I know there are easier ways to get this particular result, but it comes comes in handy when you want to iterate over the elements...

lambda versus list comprehension performance

Hi, I recently posted a question using a lambda function and in a reply someone had mentioned lambda is going out of favor, to use list comprehensions instead. I am relatively new to Python. I ran a simple test: import time S=[x for x in range(1000000)] T=[y**2 for y in range(300)] # # time1 = time.time() N=[x for x in S for y in T if...

What do backticks mean to the python interpreter: `num`

I'm playing around with list comprehensions and I came across this little snippet on another site: return ''.join([`num` for num in xrange(loop_count)]) I spent a few minutes trying to replicate the function (by typing) before realising the num bit was breaking it. What does enclosing a statement in those characters do? From what I c...

Python: complex list comprehensions where one var depends on another (x for x in t[1] for t in tests)

I want to do something like: all = [ x for x in t[1] for t in tests ] tests looks like: [ ("foo",[a,b,c]), ("bar",[d,e,f]) ] So I want to have the result all = [a,b,c,d,e,f] My code does not work, Python says: UnboundLocalError: local variable 't' referenced before assignment Is there any simple way to do that? ...

Filtering odd numbers

M = [[1,2,3], [4,5,6], [7,8,9]] col2 = [row[1] + 1 for row in M if row[1] % 2 == 0] print (col2) Output: [3, 9] I'm expecting it to filter out the odd numbers, but it does the opposite. ...

How to split the file content by space and end-of-line character?

When I do the following list comprehension I end up with nested lists: channel_values = [x for x in [ y.split(' ') for y in open(channel_output_file).readlines() ] if x and not x == '\n'] Basically I have a file composed of this: 7656 7653 7649 7646 7643 7640 7637 7634 7631 7627 7624 7621 7618 7615 8626 8623 8620 8617 8614 8610 8...

Python: create a dictionary with list comprehension

I like the python list comprehension operator (or idiom, or whatever it is). Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values: dict = {(k,v) for (k,v) in blah blah blah} # doesn't work :( ...

What are the advantage and disadvantages of using a list comprehension in Python 2.54-6?

I've heard that list comprehensions can be slow sometimes, but I'm not sure why? I'm new to Python (coming from a C# background), and I'd like to know more about when to use a list comprehension versus a for loop. Any ideas, suggestions, advice, or examples? Thanks for all the help. ...

How to rearrange this function to return the extended list in Haskell

Hi I am doing problem 68 at project euler and came up with the following code in Haskell to return the list of numbers which fit the (given) solution: lists = [n|n<- permutations [1..6] , ring n ] ring [a,b,c,d,e,f] = (length $ nub $ map sum [[d,c,b],[f,b,a],[e,a,c]]) == 1 This only returns a list of lists of 6 numbers each which f...

Running average in Python

Is there a pythonic way to build up a list that contains a running average of some function? After reading a fun little piece about Martians, black boxes, and the Cauchy distribution, I thought it would be fun to calculate a running average of the Cauchy distribution myself: import math import random def cauchy(location, scale): ...

List comprehension won't give correct result in Haskell

Hi I am doing project euler question 136, and came up with the following to test the example given: module Main where import Data.List unsum x y z n = (y > 0) && (z > 0) && (((x*x) - (y*y)- (z*z)) == n) && ((x - y) == (y - z)) answer = snub $ takeWhile (<100) [n|x<-[1..],d<-[1..x`div`2],n<-[x..100],y<-[x-d],z<-[y-d], unsum x y z n ] ...

Haskell List Comprehension

I get the error "Not in scope: x" when doing as follows... blanks :: Sudoku -> [Pos] blanks (Sudoku su) = [ fst x | x <- posSud | isBlank (snd x) ] where isBlank Nothing = True isBlank _ = False posSud = zip ixPos (concat su) ixPos = zip ixRows ixCols ixCols = concat (replicate 9 [0..8]) ixRows ...

implementing a per-digit counter using the list monad

So, I was looking at the question here, and built a rather ugly solution for the problem. While trying to clean it up, I started investigating list comprehensions and the list monad. What I decided to do was to implement a per-digit counter using the list monad. Given an input sequence of digits, [1, 2], I wanted to generate an output...

Converting a list of lists to a tuple in Python

I have a list of lists (generated with a simple list comprehension): >>> base_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)] >>> base_lists [[1,1],[1,2],[1,3],[1,4],[1,5],[2,1],[2,2],[2,3],[2,4],[2,5]] I want to turn this entire list into a tuple containing all of the values in the lists, i.e.: resulting_tuple = (1,1,1,2...