我正在寻找一种方法来转换像这样的列表
[[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)]
.........................................
答案 0 :(得分:13)
以下行应该这样做:
[list(zip(row, row[1:])) for row in m]
其中m
是您的初始二维列表
更新评论中的第二个问题
您必须transpose(=与行交换列)您的二维列表。实现m
转置的python方法是zip(*m)
:
[list(zip(column, column[1:])) for column in zip(*m)]
答案 1 :(得分:6)
回应提问者的进一步评论,有两个答案:
# 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)]
答案 2 :(得分:2)
另一个版本是使用lambda
和map
map(lambda x: zip(x,x[1:]),m)
其中m
是您选择的矩阵。
答案 3 :(得分:1)
列表推导提供了创建列表的简明方法: 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]