list-comprehension

Python-like list comprehension in Java

Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ? I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return another String as outp...

C# List Comprehensions = Pure Syntactic Sugar?

Consider the following C# code: IEnumerable numbers = Enumerable.Range(0, 10); var evens = from num in numbers where num % 2 == 0 select num; Is this pure syntactic sugar to allow me to write a for or foreach loop as a one-liner? Are there any compiler optimizations under the covers that make the list comprehension above more efficien...

Caching values in Python list comprehensions

I'm using the following list comprehension: resources = [obj.get("file") for obj in iterator if obj.get("file") != None] Is there a way to "cache" the value of obj.get("file") when it's checked in the if statement so that it doesn't have to call get again on obj when it generates the return list? ...

How can this be written on a single line?

I've seen some Python list comprehensions before, but can this be done in a single line of Python? errs = {} for f in form: if f.errors: errs[f.auto_id] = f.errors ...

How to walk up a linked-list using a list comprehension?

I've been trying to think of a way to traverse a hierarchical structure, like a linked list, using a list expression, but haven't come up with anything that seems to work. Basically, I want to convert this code: p = self.parent names = [] while p: names.append(p.name) p = p.parent print ".".join(names) into a one-liner like: pri...

is there a better way to convert a list to a dictionary in python with keys but no values?

I was sure that there would be a one liner to convert a list to a dictionary where the items in the list were keys and the dictionary had no values. The only way I could find to do it was argued against "Using list comprehensions when the result is ignored is misleading and inefficient. A for loop is better" myList=['a','b','c','d...

Does Python's heapify() not play well with list comprehension and slicing?

I found an interesting bug in a program that I implemented somewhat lazily, and wondered if I'm comprehending it correctly. The short version is that Python's heapq implementation doesn't actually order a list, it merely groks the list in a heap-centric way. Specifically, I was expecting heapify() to result in an ordered list that facili...

Why does list comprehension using a zip object results in an empty list?

f = lambda x : 2*x g = lambda x : x ** 2 h = lambda x : x ** x funcTriple = ( f, g, h ) myZip = ( zip ( funcTriple, (1, 3, 5) ) ) k = lambda pair : pair[0](pair[1]) # Why do Output # 1 (2, 9, 3125) and Output # 2 ( [ ] ) differ? print ("\n\nOutput # 1: for pair in myZip: k(pair) ...") for pair in myZip : print ( k(pair) ) print (...

python list comprehensions; compressing a list of lists?

Hi, guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. What I'm doing is this. I have a list, A, and I have a function f which takes an item and returns a list. I can use a list comprehension to convert everything in A like so; [f(a) for a in A] But...

Help needed improving Python code using List Comprehensions

I've been writing little Python programs at home to learn more about the language. The most recent feature I've tried to understand are List Comprehensions. I created a little script that estimates when my car needs its next oil change based on how frequently I've gotten the oil changed in the past. In the code snippet below, oil_chan...

Python: StopIteration exception and list comprehensions

I'd like to read at most 20 lines from a csv file: rows = [csvreader.next() for i in range(20)] Works fine if the file has 20 or more rows, fails with a StopIteration exception otherwise. Is there an elegant way to deal with an iterator that could throw a StopIteration exception in a list comprehension or should I use a regular for l...

Perl equivalent of (Python-) list comprehension

I'm looking for ways to express this Python snippet in Perl: data = {"A": None, "B": "yes", "C": None} key_list = [k for k in data if data[k]] # in this case the same as filter(lambda k: data[k], data) but let's ignore that So looking at it one way, I just want the keys where the values are None or undef. Looking at it another way, ...

Are list comprehensions a major part of Haskell

I looked at various Haskell resources on the web, before buying the book, Real World Haskell. Being otherwise excellent, it doesn't seem to contain anything about list comprehensions which I saw mentioned in the various websites I looked at. Could this just be because they are generally unused in well written Haskell for some reason, or ...

Tokenizing blocks of code in Python

I have this string: [a [a b] [c e f] d] and I want a list like this lst[0] = "a" lst[1] = "a b" lst[2] = "c e f" lst[3] = "d" My current implementation that I don't think is elegant/pythonic is two recursive functions (one splitting with '[' and the other with ']' ) but I am sure it can be done using list comprehensions or regula...

one liner for conditionally replacing dictionary values

Is there a better way to express this using list comprehension? Or any other way of expressing this in one line? I want to replace each value in the original dictionary with a corresponding value in the col dictionary, or leave it unchanged if its not in the col dictionary. col = {'1':3.5, '6':4.7} original = {'1':3, '2':1, '3':5, '4':...

Double Iteration in List Comprehension

In Python you can have multiple iterators in a list comprehension, like [(x,y) for x in a for y in b] for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions. My question is: Can one iterator in the comprehension refer to the other? In other words: Could I have something like this: ...

List Comprehensions in Python : efficient selection in a list

Hi Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a distance to an other element). I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code result = [ ( myFunction(C), C) for C in originalList if myF...

Python List Comprehension Vs. Map

Is there a reason to prefer using map() over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other? ...

Mapping a nested list with List Comprehension in Python?

I have the following code which I use to map a nested list in Python to produce a list with the same structure. >>> nested_list = [['Hello', 'World'], ['Goodbye', 'World']] >>> [map(str.upper, x) for x in nested_list] [['HELLO', 'WORLD'], ['GOODBYE', 'WORLD']] Can this be done with list comprehension alone (without using the map func...

Scala's for-comprehensions: vital feature or syntactic sugar?

When I first started looking at Scala, I liked the look of for-comprehensions. They seemed to be a bit like the foreach loops I was used to from Java 5, but with functional restrictions and a lot of sweet syntactic niceness. But as I've absorbed the Scala style, I find that every time I could use a for-comprension I'm using map, flatMap...