pythonic

What is a Pythonic way to get a list of tuples of all the possible combinations of the elements of two lists?

Suppose I have two differently-sized lists a = [1, 2, 3] b = ['a', 'b'] What is a Pythonic way to get a list of tuples c of all the possible combinations of one element from a and one element from b? >>> print c [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')] The order of elements in c does not matter. The solution wi...

Working with multiple input and output files in Python

I need to open multiple files (2 input and 2 output files), do complex manipulations on the lines from input files and then append results at the end of 2 output files. I am currently using the following approach: in_1 = open(input_1) in_2 = open(input_2) out_1 = open(output_1, "w") out_2 = open(output_2, "w") # Read one line from each...

Python performance: iteration and operations on nested lists

Problem Hey folks. I'm looking for some advice on python performance. Some background on my problem: Given: A (x,y) mesh of nodes each with a value (0...255) starting at 0 A list of N input coordinates each at a specified location within the range (0...x, 0...y) A value Z that defines the "neighborhood" in count of nodes Increm...

How to improve my Python regex syntax?

I very new to Python, and fairly new to regex. (I have no Perl experience.) I am able to use regular expressions in a way that works, but I'm not sure that my code is particularly Pythonic or consise. For example, If I wanted to read in a text file and print out text that appears directly between the words 'foo' and 'bar' in each line...

good __eq__, __lt__, ..., __hash__ methods for image class?

I create the following class: class Image(object): def __init__(self, extension, data, urls=None, user_data=None): self._extension = extension self._data = data self._urls = urls self._user_data = user_data self._hex_digest = hashlib.sha1(self._data).hexDigest() Images should be equal when a...

Tuple unpacking: dummy variable vs index

What is the usual/clearest way to write this in Python? value, _ = func_returning_a_tuple() or: value = func_returning_a_tuple()[0] ...

What's the pythonic way to use getters and setters?

I'm doing it like: def set_property(property,value): def get_property(property): or object.property = value value = object.property I'm new to Python, so i'm still exploring the syntax, and i'd like some advice on doing this. ...

Insert a newline character every 64 characters using Python

Using Python I need to insert a newline character into a string every 64 characters. In Perl it's easy: s/(.{64})/$1\n/ How could this be done using regular expressions in Python? Is there a more pythonic way to do it? ...

Python, concise way to test membership in collection using partial match

hello. What is the pythonic way to test if there is a tuple starting with another tuple in collection? actually, I am really after the index of match, but I can probably figure out from test example for example: c = ((0,1),(2,3)) # (0,) should match first element, (3,)should match no element I should add my python is 2.4 and/or 2.5...

Fast iterating over first n items of an iterable (not a list) in python

Hello! I'm looking for a pythonic way of iterating over first n items of an iterable (upd: not a list in a common case, as for lists things are trivial), and it's quite important to do this as fast as possible. This is how I do it now: count = 0 for item in iterable: do_something(item) count += 1 if count >= n: break Doesn't seem ...

a more pythonic way to express conditionally bounded loop?

I've got a loop that wants to execute to exhaustion or until some user specified limit is reached. I've got a construct that looks bad yet I can't seem to find a more elegant way to express it; is there one? def ello_bruce(limit=None): for i in xrange(10**5): if predicate(i): if not limit is None: ...

Python: does it make sense to refactor this check into its own method?

I'm still learning python. I just wrote this method to determine if a player has won a game of tic-tac-toe yet, given a board state like: '[['o','x','x'],['x','o','-'],['x','o','o']]' def hasWon(board): players = ['x', 'o'] for player in players: for row in board: if row.count(player) == 3: return player top, m...

Creating a simple command line interface (CLI) using a python server (TCP sock) and few scripts

I have a Linux box and I want to be able to telnet into it (port 77557) and run few required commands without having to access to the whole Linux box. So, I have a server listening on that port, and echos the entered command on the screen. (for now) Telnet 192.168.1.100 77557 Trying 192.168.1.100... Connected to 192.168.1....

Extract list of attributes from list of objects in python

Hi, I have an uniform list of objects in python: class myClass(object): def __init__(self, attr): self.attr = attr self.other = None objs = [myClass (i) for i in range(10)] Now I want to extract a list with some attribute of that class (let's say attr), in order to pass it so some function (for plotting that data ...

Is there a better way of making numpy.argmin() ignore NaN values

Hello Everybody, I want to get the index of the min value of a numpy array that contains NaNs and I want them ignored >>> a = array([ nan, 2.5, 3., nan, 4., 5.]) >>> a array([ NaN, 2.5, 3. , NaN, 4. , 5. ]) if I run argmin, it returns the index of the first NaN >>> a.argmin() 0 I substitute NaNs with Infs a...

"isnotnan" functionality in numpy, can this be more pythonic?

Hello Everybody, I need a function that returns non-NaN values from an array. Currently I am doing it this way: >>> a = np.array([np.nan, 1, 2]) >>> a array([ NaN, 1., 2.]) >>> np.invert(np.isnan(a)) array([False, True, True], dtype=bool) >>> a[np.invert(np.isnan(a))] array([ 1., 2.]) Python: 2.6.4 numpy: 1.3.0 Please share...

pythonic way to associate list elements with their indices

Hello Everybody, I have a list of values and I want to put them in a dictionary that would map each value to it's index. I can do it this way: >>> t = (5,6,7) >>> d = dict(zip(t, range(len(t)))) >>> d {5: 0, 6: 1, 7: 2} this is not bad, but I'm looking for something more elegant. I've come across the following, but it does the opp...

pythonic way of selecing a random value that satisfies a certain predicate

Suppose I have a list of elements and I want to randomly select an element from the list that satisfies a predicate. What is the pythonic way of doing this? I currently do a comprehension followed by a random.choice() but that is unnecessarily inefficient : intlist = [1,2,3,4,5,6,7,8,9] evenlist = [ i for i in intlist if i % 2 == 0 ]...

How can this verbose, unpythonic routine be improved?

Is there a more pythonic way of doing this? I am trying to find the eight neighbours of an integer coordinate lying within an extent. I am interested in reducing its verbosity without sacrificing execution speed. def fringe8((px, py), (x1, y1, x2, y2)): f = [(px - 1, py - 1), (px - 1, py), (px - 1, py + 1), ...

Compound dictionary keys

I have a particular case where using compound dictionary keys would make a task easier. I have a working solution, but feel it is inelegant. How would you do it? context = { 'database': { 'port': 9990, 'users': ['number2', 'dr_evil'] }, 'admins': ['[email protected]', '[email protected]'], 'domain....