在列表结构列表中翻转相同项目的特定位置

时间:2017-12-27 12:36:03

标签: python-3.x list indexing

我有以下数据结构:

pool = [[[0,0,0,0,0,0,0,0],"ze","Zero"],
[[0,0,3,0,3,0,0,0],"bd","BasicDilemma"],
[[0,0,3,2,3,0,0,2],"lk","LowLock"],
[[0,1,3,2,0,3,1,2],"DlCo",""],
[[0,1,3,2,0,3,2,1],"DlPc",""],
[[0,1,3,2,1,3,0,2],"DlAs",""],
[[0,1,3,2,1,3,2,0],"DlHa",""],
[[0,1,3,2,2,3,0,1],"DlSh",""],
[[0,1,3,2,2,3,1,0],"DlNc",""]]

def ListFlip (pool):
    for game in range (0, len(pool)):
        game[0][2], game[0][3] = game[0][3], game[0][2]
        game[0][6], game[0][7] = game[0][7], game[0][6]
    return (pool)

我需要在列表列表中的每个项目中翻转特定的索引位置,只需翻转数值。

结构将是:

[0,1,2,3,4,5,6,7] -> [0,1,3,2,4,5,7,6]

因此,对于所有项目,我需要翻转位置[2] and [3][6] and [7]

例如:

[[0,1,3,2,0,3,1,2],"DlCo",""] -> [[0,1,2,3,0,3,2,1],"DlCo",""]

我认为这将是这样做的方式,但它不起作用。有谁知道我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

这一行:

for game in range (0, len(pool)):

应该是:

for game in pool:

由于第一个只获取池中每个游戏的索引,因此索引game[0][2]在此处无效。

您的代码现在正常运行:

pool = [[[0,0,0,0,0,0,0,0],"ze","Zero"],
        [[0,0,3,0,3,0,0,0],"bd","BasicDilemma"],
        [[0,0,3,2,3,0,0,2],"lk","LowLock"],
        [[0,1,3,2,0,3,1,2],"DlCo",""],
        [[0,1,3,2,0,3,2,1],"DlPc",""],
        [[0,1,3,2,1,3,0,2],"DlAs",""],
        [[0,1,3,2,1,3,2,0],"DlHa",""],
        [[0,1,3,2,2,3,0,1],"DlSh",""],
        [[0,1,3,2,2,3,1,0],"DlNc",""]]

def ListFlip(pool):
    for game in pool:
        game[0][2], game[0][3] = game[0][3], game[0][2]
        game[0][6], game[0][7] = game[0][7], game[0][6]

    return pool

print(ListFlip(pool))

哪个输出:

[[[0, 0, 0, 0, 0, 0, 0, 0], 'ze', 'Zero'], 
 [[0, 0, 0, 3, 3, 0, 0, 0], 'bd', 'BasicDilemma'], 
 [[0, 0, 2, 3, 3, 0, 2, 0], 'lk', 'LowLock'], 
 [[0, 1, 2, 3, 0, 3, 2, 1], 'DlCo', ''], 
 [[0, 1, 2, 3, 0, 3, 1, 2], 'DlPc', ''], 
 [[0, 1, 2, 3, 1, 3, 2, 0], 'DlAs', ''], 
 [[0, 1, 2, 3, 1, 3, 0, 2], 'DlHa', ''], 
 [[0, 1, 2, 3, 2, 3, 1, 0], 'DlSh', ''], 
 [[0, 1, 2, 3, 2, 3, 0, 1], 'DlNc', '']]