4

我正在寻找一种方法来转换这样的列表

[[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]]

像这样

[[(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

4 回答 4

12

以下行应该这样做:

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

m你的初始二维列表在哪里

更新评论中的第二个问题

您必须转置(= 用行交换列)您的二维列表。实现转置的python方法mzip(*m)

[list(zip(column, column[1:])) for column in zip(*m)]
于 2012-08-27T13:49:29.537 回答
5

针对提问者的进一步评论,有两个答案:

# 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)]

原始问题:

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

更新的问题:

# 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)]
于 2012-08-27T13:45:21.750 回答
1

另一个版本是使用lambdamap

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

m您选择的矩阵在哪里。

于 2012-08-27T14:31:54.830 回答
0

列表推导提供了一种创建列表的简洁方法: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] 
于 2012-08-27T13:52:58.540 回答