简体   繁体   English

分离/访问像[[[[x,y],z],p]这样的三元组列表?

[英]Separating/accessing a triple tuple list like [[[x,y],z],p]?

I am trying to access variables stored in a triple tuple list in python and I am not sure how to do it. 我正在尝试访问存储在python三元组列表中的变量,但不确定如何执行。 I would like to be able to go through the list in a for loop and get x,y,x, & p from each tuple. 我希望能够在for循环中浏览列表,并从每个元组获取x,y,x,&p。 How would I do that? 我该怎么办?

MovesList = [  [[[1,2],3],1] , [[[2,5],3],1] , [[[1,3],0],2]  ]

You can unpack tuples as you iterate over them: 您可以在遍历元组时解压缩它们:

Python 2: Python 2:

>>> for ((x,y),z),p in MovesList:
...     print x, y, z, p

Python 3: Python 3:

>>> for ((x,y),z),p in MovesList:
...     print(x,y,z,p)

Both of which result in: 两者都会导致:

1 2 3 1
2 5 3 1
1 3 0 2

same unpacking with list comprehension 与列表理解相同的解压缩

In [202]: [[x,y,z,p] for ([[x,y],z],p) in MovesList]
Out[202]: [[1, 2, 3, 1], [2, 5, 3, 1], [1, 3, 0, 2]]

I also found you can unpack a list of tuples that doesn't have a finite space by putting it through a while loop like so: 我还发现,可以通过如下所示的while循环来打开没有有限空间的元组列表:

Mylist = list()
MyOtherList = list()
//list is packed my tuples of four {(a,b,c,d),(a,b,c,d),(a,b,c,d),...}
While MyList[0] != Null:
     var w = MyList[0][0]
     var x = MyList[0][1]
     var y = MyList[0][2]
     var z = MyList[0][3]
     MyList.Remove(w,x,y,z)
     //do something with w,x,y,z based upon use
     MyOtherList = getMoreListItems(w,x,y,z)
     MyList.extend(MyOtherList)

This can be used when the list you would like to iterate through is full of tuples of all the same size 当您要遍历的列表中充满了所有相同大小的元组时,可以使用此方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM