【问题标题】:Only first index of tuples list being used仅使用元组列表的第一个索引
【发布时间】:2018-04-16 02:44:53
【问题描述】:

我目前正在使用 Zip 函数返回一个元组列表:

返回数据为:[(13, 3), (12, 3), (11, 3), (10, 3), (9, 3), (8, 3), (6, 3), (5, 3), (4, 3)]

我正在循环使用数据,但目前只打印第一个索引。

CheckPath = self.CheckQueenPathDown(QueenRowColumn,TheComparisonQueen) #This is where the list of tuples is being used
print(CheckPath) # this shows all the correct data when i print it.
for TheQueenMoves in QueenMoves:
    for a,b in list(self.pieces.items()):
        for CheckThePath in CheckPath:
             if TheComparisonQueen == TheQueenMoves and TheComparisonQueen[0] >= 0 and TheComparisonQueen[1] <= 7 and \
                TheComparisonQueen[1] >= 0 and TheComparisonQueen[0] <= 7 and CheckThePath != b: # this is the line im trying to use it in.
                self.placepiece(piece, row = MoveRow, column = MoveColumn)
                print(CheckThePath)

这是我从中获取信息的代码:

 Example data: 
 QueenRowColumn: (3,3)
 TheComparisonQueen: (7,3)

 def CheckQueenPathDown(self, QueenRowColumn, TheComparisonQueen):


row = []
column = []

CurrentLocation = QueenRowColumn
#MoveLocation = TheComparisonQueen
a = QueenRowColumn[0]
b = QueenRowColumn[1]

for i in range (-10,0):

    row.append(CurrentLocation[1] - i)
    column.append(a)

Down = zip(row,column)

#Down.remove(TheComparisonQueen)

return Down

我目前试图通过循环使用返回数据的所有变量,但是当我打印它时只出现第一个索引,我不明白问题是什么。知道如何解决这个问题吗?

【问题讨论】:

  • 我猜你需要指定CheckThePath 的索引,比如CheckThePath[0]或者CheckThePath[1]
  • 当然可以,但是循环没有遍历所有数据是否有原因?
  • 你能简单地在第一行之后打印出循环中的项目吗?for c in Checkpath: print c[0],c[1]
  • 我可以打印出元组(13,3) 的前两个索引133,但是当我尝试再打印时,我得到Tuple index out of range 错误。意味着其他变量没有被循环。
  • a = [1,2,3,4,5] b = [1,2,3,4,5] for item in zip(a,b): print(item[0],item[1])我无法重现问题

标签: python-3.x list for-loop tuples


【解决方案1】:

zip 不会在 Python 3 上创建列表。如果您需要列表,请在结果上调用 list

在 Python 3 上,zip 返回一个迭代器,它在迭代一次后就耗尽了。如果您尝试重复使用它,您将无法从中获得任何元素。

【讨论】:

  • 我在返回的数据上调用了一个列表,我仍然得到相同的结果。
【解决方案2】:

试试:

def CheckQueenPathDown(self, QueenRowColumn, TheComparisonQueen):


    row = []
    column = []

    CurrentLocation = QueenRowColumn
    #MoveLocation = TheComparisonQueen
    a = QueenRowColumn[0]
    b = QueenRowColumn[1]

    for i in range (-10,0):

        row.append(CurrentLocation[1] - i)
        column.append(a)

    Down = zip(row,column)

    #Down.remove(TheComparisonQueen)

    return list(Down)

由于return list(ZIP_OBJ) 会为其分配内存,因此您可以在嵌套循环中重复使用它。

【讨论】:

  • 顺便说一句,我没有发布我的所有代码,我只是发现在第一个之后如果数据似乎消失了,我在第一个 If 之后打印了数据并且它在那里,第三个 if只剩下第一个元组。如果有关系吗?
  • 没关系,即使在第一个if 信息消失后,我也不知道发生了什么。
猜你喜欢
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
  • 1970-01-01
  • 2020-12-15
  • 1970-01-01
  • 2020-04-08
  • 2013-07-30
相关资源
最近更新 更多