Convert Lists

I am looking for a way to convert a list like this

[[1.1, 1.2, 1.3, 1.4, 1.5], [2.1, 2.2, 2.3, 2.4, 2.5], [3.1, 3.2, 3.3, 3.4, 3.5], [4.1, 4.2, 4.3, 4.4, 4.5], [5.1, 5.2, 5.3, 5.4, 5.5]] 

to something like this

 [[(1.1,1.2),(1.2,1.3),(1.3,1.4),(1.4,1.5)], [(2.1,2.2),(2.2,2.3),(2.3,2.4),(2.4,2.5)] ......................................... 
+4
source share
4 answers

In response to the respondent's further comments, two answers:

 # Original grid grid = [[1.1, 1.2, 1.3, 1.4, 1.5], [2.1, 2.2, 2.3, 2.4, 2.5], [3.1, 3.2, 3.3, 3.4, 3.5], [4.1, 4.2, 4.3, 4.4, 4.5], [5.1, 5.2, 5.3, 5.4, 5.5]] # Window function to return sequence of pairs. def window(row): return [(row[i], row[i + 1]) for i in range(len(row) - 1)] 

ORIGINAL QUESTION:

 # Print sequences of pairs for grid print [window(y) for y in grid] 

UPDATED QUESTION:

 # Take the nth item from every row to get that column. def column(grid, columnNumber): return [row[columnNumber] for row in grid] # Transpose grid to turn it into columns. def transpose(grid): # Assume all rows are the same length. numColumns = len(grid[0]) return [column(grid, columnI) for columnI in range(numColumns)] # Return windowed pairs for transposed matrix. print [window(y) for y in transpose(grid)] 
+6
source

The following line should do this:

 [list(zip(row, row[1:])) for row in m] 

where m is your initial two-dimensional list

UPDATE for the second question in the comment

You must transpose (= exchange columns with rows) your two-dimensional list. The python path to achieve transposition of m is zip(*m) :

 [list(zip(column, column[1:])) for column in zip(*m)] 
+13
source

Another version is to use lambda and map

 map(lambda x: zip(x,x[1:]),m) 

where m is your selection matrix.

+2
source

The list explanations provide a quick way to create lists: http://docs.python.org/tutorial/datastructures.html#list-comprehensions

 [[(a[i],a[i+1]) for i in xrange(len(a)-1)] for a in A] 
+1
source

All Articles