list-comprehension

Generator Expressions vs. List Comprehension

When should you use generator expressions vs. list comprehensions in Python and vice-versa? # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] ...

How do I merge a 2D array in Python into one string with List Comprehension?

List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers. Say, I have a 2D list: li = [[0,1,2],[3,4,5],[6,7,8]] I would like to merge this either into one long list li2 = [0,1,2,3,4,5,6,7,8] or into a string with separators: s = "0,1,2,3,4,5,6,7,8" Really, I'd l...

How do I efficiently filter computed values within a Python list comprehension?

The Python list comprehension syntax makes it easy to filter values within a comprehension. For example: result = [x**2 for x in mylist if type(x) is int] Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you want to filter on the result? One option is: result...

List Comprehension Library for Scheme?

I know there is a list-comprehension library for common lisp (incf-cl), I know they're supported natively in various other functional (and some non-functional) languages (F#, Erlang, Haskell and C#) - is there a list comprehension library for Scheme? incf-cl is implemented in CL as a library using macros - shouldn't it be possible to us...

Why results of map() and list comprehension are different?

The following test fails: #!/usr/bin/env python def f(*args): """ >>> t = 1, -1 >>> f(*map(lambda i: lambda: i, t)) [1, -1] >>> f(*(lambda: i for i in t)) # -> [-1, -1] [1, -1] >>> f(*[lambda: i for i in t]) # -> [-1, -1] [1, -1] """ alist = [a() for a in args] print(alist) if __name__ == '__...

Most pythonic way of counting matching elements in something iterable

I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three. My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the split loop refactoring in mind), looks rath...

List Comprehension in an Open Office Spreadsheet

List Comprehension is a very useful code mechanism that is found in several languages, such as Haskell, Python, and Ruby (just to name a few off the top of my head). I'm familiar with the construct. I find myself working on an Open Office Spreadsheet and I need to do something fairly common: I want to count all of the values in a range ...

Unexpected list comprehension behaviour in Python.

I believe I'm getting bitten by some combination of nested scoping rules and list comprehensions. Jeremy Hylton's blog post is suggestive about the causes, but I don't really understand CPython's implementation well-enough to figure out how to get around this. Here is an (overcomplicated?) example. If people have a simpler one that d...

Flattening a shallow list in Python

On a Django project, I was hoping to flatten a shallow list with a nested list comprehension, like this: [image for image in menuitem.image_set.all() for menuitem in list_of_menuitems] But I get in trouble of the NameError variety there, because the name 'menuitem' is not defined. After googling and looking around on Stack Overflow, ...

What's the most efficient way to access sibling dictionary value in a Python dict?

In Python, I've got a list if dictionaries that looks like this: matchings = [ {'id': 'someid1', 'domain': 'somedomain1.com'}, {'id': 'someid2', 'domain': 'somedomain2.com'}, {'id': 'someid3', 'domain': 'somedomain3.com'} ] and, I have a variable: the_id = 'someid3' What's the most efficient way to retrieve the domain v...

Python: For each list element apply a function across the list

Given [1,2,3,4,5], how can i do something like 1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case i've described above i would like to return (1,5). So basically I would like to do somethin...

Problem in understanding Python list comprehensions

What does the last line mean in the following code? import pickle, urllib handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p") data = pickle.load(handle) handle....

Can you create more than one element of a list at a time with a list comprehension in haskell?

So, for example, say I had a list of numbers and I wanted to create a list that contained each number multiplied by 2 and 3. Is there any way to do something like the following, but get back a single list of numbers instead of a list of lists of numbers? mult_nums = [ [(n*2),(n*3)] | n <- [1..5]] -- this returns [[2,3],[4,6],[6,9],[8,1...

Use case for nested/multiple list comprehensions or generator expressions. When is it more elegant?

I see this kind of thing sometimes: (k for k in (j for j in (i for i in xrange(10)))) Now this really bends my brain, and I would rather it wasn't presented in this way. Are there any use-cases, or examples of having used these nested expressions where it was more elegant and more readable than if it had been a nested loop? Edit: Th...

Why don't Haskell list comprehensions cause an error when pattern match fails?

I'm trying to understand how Haskell list comprehensions work "under the hood" in regards to pattern matching. The following ghci output illustrates my point: Prelude> let myList = [Just 1, Just 2, Nothing, Just 3] Prelude> let xs = [x | Just x <- myList] Prelude> xs [1,2,3] Prelude> As you can see, it is able to skip the "Nothing" an...

how to express {2n+3m+1|n,m∈N} in list comprehension form? ( N is the set of natraul number including 0)

How do I express {2n+3m+1|n,m∈N} in list comprehension form? N is the set of natural numbers, including 0. ...

Spliting a file into lines in Python using re.split

I'm trying to split a file with a list comprehension using code similar to: lines = [x for x in re.split(r"\n+", file.read()) if not re.match(r"com", x)] However, the lines list always has an empty string as the last element. Does anyone know a way to avoid this (excluding the cludge of putting a pop() afterwards)? ...

Can I use a List Comprehension to get Line Indexes from a file?

I need to identify some locations in a file where certain markers might be. I started off thinking that I would use list.index but I soon discovered that returns the first (and only the first) item. so I decided to implement my own solution which was count=0 docIndex=[] for line in open('myfile.txt','r'): if 'mystring' in line: ...

how do i translate this Haskell to F#?

I'm trying to learn F# by translating some Haskell code I wrote a very long time ago, but I'm stuck! percent :: Int -> Int -> Float percent a b = (fromInt a / fromInt b) * 100 freqs :: String -> [Float] freqs ws = [percent (count x ws) (lowers ws) | x <- ['a' .. 'z']] I've managed this: let percent a b = (floa...

Python's most efficient way to choose longest string in list?

I have a list of variable length and am trying to find (most likely) a list comprehension to allow me to see if the list item currently being evaluated is the longest string contained in the list. And am using Pythong 2.6.1 ie. mylist = ['123','123456','1234'] for each in mylist: if condition1: do_something() elif ____...