list-comprehension

Why doesn't this list comprehension do what I expect it to do?

The original list project_keys = sorted(projects.keys()) is [101, 102, 103, 104, 105, 106, 107, 108, 109, 110] where the following projects were deemed invalid this year: 108, 109, 110. Thus: for project in projects.itervalues(): # The projects dictionary is mapped to the Project class if project.invalid: # Where invalid is a...

Is it possible to use 'else' in a python list comprehension?

Here is the code I was trying to turn into a list comprehension: table = '' for index in xrange(256): if index in ords_to_keep: table += chr(index) else: table += replace_with Is there a way to add the else statement to this comprehension? table = ''.join(chr(index) for index in xrange(15) if index in ords_to_...

Counting entries in a list of dictionaries: for loop vs. list comprehension with map(itemgetter)

In a Python program I'm writing I've compared using a for loop and increment variables versus list comprehension with map(itemgetter) and len() when counting entries in dictionaries which are in a list. It takes the same time using a each method. Am I doing something wrong or is there a better approach? Here is a greatly simplified and ...

finding elements in python association lists efficiently

I have a set of lists that look like this: conditions = [ ["condition1", ["sample1", "sample2", "sample3"]], ["condition2", ["sample4", "sample5", "sample6"], ...] how can I do the following things efficiently and elegantly in Python? Find all the elements in a certain condition? e.g. get all the samples in condition2. Right now I...

Python - How to find a correlation between two vectors?

Given two vectors X and Y, I have to find their correlation, i.e. their linear dependence/independence. Both vectors have equal dimension. The result should be a floating point number from [-1.0 .. 1.0]. Example: X=[-1, 2, 0] Y=[ 4, 2, -0.3] Find y = cor(X,Y) such that y belongs to [-1.0 .. 1.0]. It should be a simple construct...

Better Way to Write This List Comprehension?

I'm parsing a string that doesn't have a delimiter but does have specific indexes where fields start and stop. Here's my list comprehension to generate a list from the string: field_breaks = [(0,2), (2,10), (10,13), (13, 21), (21, 32), (32, 43), (43, 51), (51, 54), (54, 55), (55, 57), (57, 61), (61, 63), (63, 113), (113, 163), (163, 213...

Python dictionaries: changing the order of nesting

I have a dictionary, with 300 key value pairs, where each of the keys are integers and the values are dictionaries with three key value pairs. The inner dictionaries all have the same keys, but different values. The whole thing looks pretty much like this: nested_dicts = {1: {'name1':88.4, 'name2':22.1, 'name3':115.7}, 2: {'...

How to use list comprehension to add an element to copies of a dictionary?

given: template = {'a': 'b', 'c': 'd'} add = ['e', 'f'] k = 'z' I want to use list comprehension to generate [{'a': 'b', 'c': 'd', 'z': 'e'}, {'a': 'b', 'c': 'd', 'z': 'f'}] I know I can do this: out = [] for v in add: t = template.copy() t[k] = v out.append(t) but it is a little verbose and has no advantage over what I'm...

How do I convert a tuple of tuples to a one-dimensional list using list comprehension?

I have a tuple of tuples - for example: tupleOfTuples = ((1, 2), (3, 4), (5,)) I want to convert this into a flat, one-dimensional list of all the elements in order: [1, 2, 3, 4, 5] I've been trying to accomplish this with list comprehension. But I can't seem to figure it out. I was able to accomplish it with a for-each loop: myLi...

Python list comprehension for dictionaries in dictionaries?

I just learned about list comprehension, which is a great fast way to get data in a single line of code. But something's bugging me. In my test I have this kind of dictionaries inside the list: [{'y': 72, 'x': 94, 'fname': 'test1420'}, {'y': 72, 'x': 94, 'fname': 'test277'}] The list comprehension s = [ r for r in list if r['x'] > 92...

Optimize a list comprehension

Here is a code snippet that shows the code I would like to optimize: result = [(item, foo(item)) for item in item_list if cond1(item) and cond2(foo(item))] In the above snippet I call foo(item) twice. I can't think of a way to iterate over the list only once maintain both item and foo(item) for the conditional and ...

Multiple yields in sequence comprehension?

I'm trying to learn Scala and tried to write a sequence comprehension that extracts unigrams, bigrams and trigrams from a sequence. E.g., [1,2,3,4] should be transformed to (not Scala syntax) [1; _,1; _,_,1; 2; 1,2; _,1,2; 3; 2,3; 1,2,3; 4; 3,4; 2,3,4] In Scala 2.8, I tried the following: def trigrams(tokens : Seq[T]) = { var t1 : ...

Pythonic way to turn a list of strings into a dictionary with the odd-indexed strings as keys and even-indexed ones as values?

I have a list of strings parsed from somewhere, in the following format: [key1, value1, key2, value2, key3, value3, ...] I'd like to create a dictionary based on this list, like so: {key1:value1, key2:value2, key3:value3, ...} An ordinary for loop with index offsets would probably do the trick, but I wonder if there's a Pythonic wa...

Python list, lookup object name, efficiency advice

Suppose I have the following object: class Foo(object): def __init__(self, name=None): self.name = name def __repr__(self): return self.name And a list containing multiple instances, such as: list = [Foo(name='alice'), Foo(name='bob'), Foo(name='charlie')] If I want to find an object with a given name, I could use the ...

Would it be very unpythonic to use this setitem function to overcome the list comprehension limitation?

>>> a=range(5) >>> [a[i] for i in range(0,len(a),2)] ## list comprehension for side effects [0, 2, 4] >>> a [0, 1, 2, 3, 4] >>> [a[i]=3 for i in range(0,len(a),2)] ## try to do assignment SyntaxError: invalid syntax >>> def setitem(listtochange,n,value): ## function to overcome limitation listtochange[n]=value return value >>> ...

How to counting not 0 elements in an iterable?

I'm looking for a better/more Pythonic solution for the following snippet count = sum(1 for e in iterable if e) ...

Generator in if-statement in python

Or How to if-statement in a modified list. I've been reading StackOverflow for a while (thanks to everyone). I love it. I also seen that you can post a question and answer it yourself. Sorry if I duplicate, but I didn't found this particular answer on StackOverflow. How do you verify if a element is in a list but modify it in the sa...

How does this Haskell function to calculate permutations using list comprehension work?

I'm reading Simon Thompson's Haskell: The Craft of Functional Programming, and I'm wondering how does this work: perms [] = [[]] perms xs = [ x:ps | x <- xs , ps <- perms ( xs\\[x] ) ] I can't seem to grasp how that perms( xs\\[x] ) is supposed to function. The trace of a two element list shows: perms [2,3] [ x:ps | x <- [2,3] , ps...

List comprehension for running total

I want to get a running total from a list of numbers. For demo purposes, I start with a sequential list of numbers using range a = range(20) runningTotal = [] for n in range(len(a)): new = runningTotal[n-1] + a[n] if n > 0 else a[n] runningTotal.append(new) # This one is a syntax error # runningTotal = [a[n] for n in range(le...

How to remove list of words from a list of strings

Sorry if the question is bit confusing. This is similar to this question I think this the above question is close to what I want, but in Clojure. There is another question I need something like this but instead of '[br]' in that question, there is a list of strings that need to be searched and removed. Hope I made myself clear. I...