Search Results

Search found 149 results on 6 pages for 'comprehension'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • Python nested dict comprehension with sets

    - by Jasie
    Can someone explain how to do nested dict comprehensions? >> l = [set([1, 2, 3]), set([4, 5, 6])] >> j = dict((a, i) for a in s for i, s in enumerate(l)) >> NameError: name 's' is not defined I would have liked: >> j >> {1:0, 2:0, 3:0, 4: 1, 5: 1, 6: 1} I just asked a previous question about a simpler dict comprehension where the parentheses in the generator function were reduced. How come the s in the leftmost comprehension is not recognized?

    Read the article

  • Python: Repeat elements in a list comprehension?

    - by User
    I have the following list comprehension which returns a list of coordinate objects for each location. coordinate_list = [Coordinates(location.latitude, location.longitude) for location in locations] This works. Now suppose the location object has a number_of_times member. I want a list comprehension to generate n Coordinate objects where n is the number_of_times for the particular location. So if a location has number_of_times = 5 then the coordinates for that location will be repeated 5 times in the list. (Maybe this is a case for a for-loop but I'm curious if it can be done via list comprehensions)

    Read the article

  • Help with python list-comprehension

    - by leChuck
    A simplified version of my problem: I have a list comprehension that i use to set bitflags on a two dimensional list so: s = FLAG1 | FLAG2 | FLAG3 [[c.set_state(s) for c in row] for row in self.__map] All set_state does is: self.state |= f This works fine but I have to have this function "set_state" in every cell in __map. Every cell in __map has a .state so what I'm trying to do is something like: [[c.state |= s for c in row] for row in self.map] or map(lambda c: c.state |= s, [c for c in row for row in self.__map]) Except that neither works (Syntax error). Perhaps I'm barking up the wrong tree with map/lamda but I would like to get rid on set_state. And perhaps know why assignment does not work in the list-comprehension

    Read the article

  • List comprehension from multiple sources in Python?

    - by Noah
    Is it possible to replace the following with a list comprehension? res = [] for a, _, c in myList: for i in c: res.append((a, i)) For example: # Input myList = [("Foo", None, [1, 2, 3]), ("Bar", None, ["i", "j"])] # Output res = [("Foo", 1), ("Foo", 2), ("Foo", 3), ("Bar", "i"), ("Bar", "j")]

    Read the article

  • Python 3: unpack inner lists in list comprehension

    - by Beau Martínez
    I'm running the following code on a list of strings to return a list of its words: words = [re.split('\\s+', line) for line in lines] However, I end up getting something like: [['import', 're', ''], ['', ''], ['def', 'word_count(filename):', ''], ...] As opposed to the desired: ['import', 're', '', '', '', 'def', 'word_count(filename):', '', ...] How can I unpack the lists re.split('\\s+', line) produces in the above list comprehension? Naïvely, I tried using * but that doesn't work. (I'm looking for a simple and Pythonic way of doing; I was tempted to write a function but I'm sure the language accommodates for this issue.)

    Read the article

  • Erlang list comprehension, traversing two lists and excluding values

    - by ErJab
    I need to generate a set of coordinates in Erlang. Given one coordinate, say (x,y) I need to generate (x-1, y-1), (x-1, y), (x-1, y+1), (x, y-1), (x, y+1), (x+1, y-1), (x+1, y), (x+1, y+1). Basically all surrounding coordinates EXCEPT the middle coordinate (x,y). To generate all the nine coordinates, I do this currently: [{X,Y} || X<-lists:seq(X-1,X+1), Y<-lists:seq(Y-1,Y+1)] But this generates all the values, including (X,Y). How do I exclude (X,Y) from the list using filters in the list comprehension?

    Read the article

  • Python list comprehension to return edge values of a list

    - by mvid
    If I have a list in python such as: stuff = [1, 2, 3, 4, 5, 6, 7, 8, 9] with length n (in this case 9) and I am interested in creating lists of length n/2 (in this case 4). I want all possible sets of n/2 values in the original list, for example: [1, 2, 3, 4], [2, 3, 4, 5], ..., [9, 1, 2, 3] is there some list comprehension code I could use to iterate through the list and retrieve all of those sublists? I don't care about the order of the values within the lists, I am just trying to find a clever method of generating the lists.

    Read the article

  • Python list comprehension overriding value

    - by Joschua
    Hi, folks have a look at the following piece of code, which shows a list comprehension.. >>> i = 6 >>> s = [i * i for i in range(100)] >>> print(i) When you execute the code example in Python 2.6 it prints 99, but when you execute it in Python 3.x it prints 6. What were the reason for changing the behaviour and why is the output 6 in Python 3.x? Thank you in advance!

    Read the article

  • scala: how to rewrite this function using for comprehension

    - by opensas
    I have this piece of code with a couple of nasty nested checks... I'm pretty sure it can be rewritten with a nice for comprehension, but I'm a bit confused about how to mix the pattern matching stuff // first tries to find the token in a header: "authorization: ideas_token=xxxxx" // then tries to find the token in the querystring: "ideas_token=xxxxx" private def applicationTokenFromRequest(request: Request[AnyContent]): Option[String] = { val fromHeaders: Option[String] = request.headers.get("authorization") val tokenRegExp = """^\s*ideas_token\s*=\s*(\w+)\s*$""".r val tokenFromHeader: Option[String] = { if (fromHeaders.isDefined) { val header = fromHeaders.get if (tokenRegExp.pattern.matcher(header).matches) { val tokenRegExp(extracted) = header Some(extracted) } else { None } } else { None } } // try to find it in the queryString tokenFromHeader.orElse { request.queryString.get("ideas_token") } } any hint you can give me?

    Read the article

  • Advanced Python list comprehension

    - by Yuval A
    Given two lists: chars = ['ab', 'bc', 'ca'] words = ['abc', 'bca', 'dac', 'dbc', 'cba'] how can you use list comprehensions to generate a filtered list of words by the following condition: given that each word is of length n and chars is of length n as well, the filtered list should include only words that each i-th character is in the i string in words. In this case, we should get ['abc', 'bca'] as a result. (If this looks familiar to anyone, this was one of the questions in the previous Google code jam)

    Read the article

  • Optimizing list comprehension to find pairs of co-prime numbers

    - by user3685422
    Given A,B print the number of pairs (a,b) such that GCD(a,b)=1 and 1<=a<=A and 1<=b<=B. Here is my answer: return len([(x,y) for x in range(1,A+1) for y in range(1,B+1) if gcd(x,y) == 1]) My answer works fine for small ranges but takes enough time if the range is increased. such as 1 <= A <= 10^5 1 <= B <= 10^5 is there a better way to write this or can this be optimized?

    Read the article

  • Yet another list comprehension question

    - by relima
    I had this: if Setting["Language"] == "en": f.m_radioBox3.SetSelection(0) elif Setting["Language"] == "pt": f.m_radioBox3.SetSelection(1) elif Setting["Language"] == "fr": f.m_radioBox3.SetSelection(2) elif Setting["Language"] == "es": f.m_radioBox3.SetSelection(3) Then I did this: Linguas = ["en","pt","fr","es"] a = 0 for i in Linguas: if i == Setting["Language"]: f.m_radioBox3.SetSelection(a) a += 1 Is it possible to further simplify this and make it into a one-liner?

    Read the article

  • Cleaner method for list comprehension clean-up

    - by Dan McGrath
    This relates to my previous question: Converting from nested lists to a delimited string I have an external service that sends data to us in a delimited string format. It is lists of items, up to 3 levels deep. Level 1 is delimited by '|'. Level 2 is delimited by ';' and level 3 is delimited by ','. Each level or element can have 0 or more items. An simplified example is: a,b;c,d|e||f,g|h;; We have a function that converts this to nested lists which is how it is manipulated in Python. def dyn_to_lists(dyn): return [[[c for c in b.split(',')] for b in a.split(';')] for a in dyn.split('|')] For the example above, this function results in the following: >>> dyn = "a,b;c,d|e||f,g|h;;" >>> print (dyn_to_lists(dyn)) [[['a', 'b'], ['c', 'd']], [['e']], [['']], [['f', 'g']], [['h'], [''], ['']]] For lists, at any level, with only one item, we want it as a scalar rather than a 1 item list. For lists that are empty, we want them as just an empty string. I've came up with this function, which does work: def dyn_to_min_lists(dyn): def compress(x): return "" if len(x) == 0 else x if len(x) != 1 else x[0] return compress([compress([compress([item for item in mv.split(',')]) for mv in attr.split(';')]) for attr in dyn.split('|')]) Using this function and using the example above, it returns: [[['a', 'b'], ['c', 'd']], 'e', '', ['f', 'g'], ['h', '', '']] Being new to Python, I'm not confident this is the best way to do it. Are there any cleaner ways to handle this? This will potentially have large amounts of data passing through it, are there any more efficient/scalable ways to achieve this?

    Read the article

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

    - by Josh
    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_keep) Also, would I be right in concluding that a list comprehension is the most efficient way to do this?

    Read the article

  • Python: Multi list comprehension, is there such an unwieldy beast of prey ?

    - by bandana
    consider the following python 'code'. it demonstrates the concept of a multi-list comprehension: start = ['a', 'b', 'c'] middle = ['r', 'a', 'a'] finish = ['t', 'r', 't'] l = [s.upper() + m + f for s in start, m in middle, e in finish] >>> print l ['Art', 'Bar', 'Cat'] Alas, the above code does not work in python. What would be a good approximation of multi-list comprehension in python? Please discuss what happens when the lists have different lengths.

    Read the article

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

    - by Az
    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 Bool parameter in the Project class project_keys.remove(project.proj_id) print project_keys This will return a list of integers (which are project id's) as such: [101, 102, 103, 104, 105, 106, 107] Sweet. Now, I wanted it try the same thing using a list comprehension. project_keys = [project_keys.remove(project.proj_id) for project in projects.itervalues() if project.invalid print project_keys This returns: [None, None, None] So I'm populating a list with the same number as the removed elements but they're Nones? Can someone point out what I'm doing wrong? Additionally, why would I use a list comprehension over the for-if block at the top? Conciseness? Looks nicer?

    Read the article

  • Using list comprehension in Python to do something similar to zip()?

    - by jamieb
    I'm a Python newbie and one of the things I am trying to do is wrap my head around list comprehension. I can see that it's a pretty powerful feature that's worth learning. cities = ['Chicago', 'Detroit', 'Atlanta'] airports = ['ORD', 'DTW', 'ATL'] print zip(cities,airports) [('Chicago', 'ORD'), ('Detroit', 'DTW'), ('Atlanta', 'ATL')] How do I use list comprehension so I can get the results as a series of lists within a list, rather than a series of tuples within a list? [['Chicago', 'ORD'], ['Detroit', 'DTW'], ['Atlanta', 'ATL']] (I realize that dictionaries would probably be more appropriate in this situation, but I'm just trying to understand lists a bit better). Thanks!

    Read the article

  • Possible to capture the returned value from a Python list comprehension for use a condition?

    - by Joe
    I want to construct a value in a list comprehension, but also filter on that value. For example: [expensive_function(x) for x in generator where expensive_function(x) < 5] I want to avoid calling expensive_function twice per iteration. The generator may return an infinite series, and list comprehensions aren't lazily evaluated. So this wouldn't work: [y in [expensive_function(x) for x in generator where expensive_function(x)] where y < 5] I could write this another way, but it feels right for a list comprehension and I'm sure this is a common usage pattern (possible or not!).

    Read the article

  • Resources for improving your comprehension of recursion?

    - by Andrew M
    I know what recursion is (when a patten reoccurs within itself, typically a function that calls itself on one of its lines, after a breakout conditional... right?), and I can understand recursive functions if I study them closely. My problem is, when I see new examples, I'm always initially confused. If I see a loop, or a mapping, zipping, nesting, polymorphic calling, and so on, I know what's going just by looking at it. When I see recursive code, my thought process is usually 'wtf is this?' followed by 'oh it's recursive' followed by 'I guess it must work, if they say it does.' So do you have any tips/plans/resources for building up your skills in this area? Recursion is kind of a wierd concept so I'm thinking the way to tackle it may be equally wierd and inobvious.

    Read the article

  • list comprehension example

    - by self
    can we use elif in list comprehension? example : l = [1, 2, 3, 4, 5] for values in l: if values==1: print 'yes' elif values==2: print 'no' else: print 'idle' can we use list comprehension for such 2 if conditions and one else condition? foe example answer like : ['yes', 'no', 'idle', 'idle', 'idle'] I have done till now only if else in list comprehension.

    Read the article

  • What do you do when you feel you need a variatic list comprehension?

    - by cspyr0
    I would like to make a method where I could give it a list of lengths and it would return all combinations of cartesian coordinates up to those lengths. Easier to explain with an example: cart [2,5] Prelude> [ [0,0],[0,1],[0,2],[0,3],[0,4],[1,0],[1,1],[1,2],[1,3],[1,4] ] cart [2,2,2] Prelude> [ [0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1] ] A simple list comprehension won't work because I don't know how long the lists are going to be. While I love Haskell's simplicity for many problems, this is one that I could write procedurally (in C or something) in 5 minutes whereas Haskell gives me an aneurysm! A solution to this specific problem would help me out a lot; I'd also love to hear about your thought processes when tackling stuff like this.

    Read the article

  • What do you do when you feel you need a variadic list comprehension?

    - by cspyr0
    I would like to make a method where I could give it a list of lengths and it would return all combinations of cartesian coordinates up to those lengths. Easier to explain with an example: cart [2,5] Prelude> [ [0,0],[0,1],[0,2],[0,3],[0,4],[1,0],[1,1],[1,2],[1,3],[1,4] ] cart [2,2,2] Prelude> [ [0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1] ] A simple list comprehension won't work because I don't know how long the lists are going to be. While I love Haskell's simplicity for many problems, this is one that I could write procedurally (in C or something) in 5 minutes whereas Haskell gives me an aneurysm! A solution to this specific problem would help me out a lot; I'd also love to hear about your thought processes when tackling stuff like this.

    Read the article

1 2 3 4 5 6  | Next Page >