I am trying to access variables stored in a triple tuple list in python and I am not sure how to do it. I would like to be able to go through the list in a for loop and get x,y,x, & p from each tuple. 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:
>>> for ((x,y),z),p in MovesList:
... print x, y, z, p
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.