【问题标题】:Flipping specific positions of the same items in a list of lists structure翻转列表结构列表中相同项目的特定位置
【发布时间】:2017-12-27 12:36:03
【问题描述】:

我有以下数据结构:

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",""]

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

谢谢!

【问题讨论】:

  • 我还是没有得到最终的格式。什么是“翻转规则”?在您的示例中,有些元素被翻转,有些则没有,您并没有翻转每个位置......那么“做它的方式”是什么,那不起作用?
  • 列表中的元素有自己的结构,没有翻转。我需要翻转上述位置的项目,因此索引的规则只有 2for3 和 6for7。我尝试的方式是这个ListFlip()函数。

标签: python-3.x list indexing


【解决方案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', '']]

【讨论】:

  • 非常感谢,我想我不会很快发现这个!
  • 没问题,您只是获取索引而不是列表本身。
猜你喜欢
  • 2019-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
  • 1970-01-01
  • 2014-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多