Manipulating lists in lists in python

I am having trouble moving my head around working with lists in lists in python (I'm pretty new to programming).

Now, how can I access each position of the nested list, and then manipulate the position of the nested values ​​of the list, for example, reorder, keeping the position of the nested list in the main list.

For example: if I wanted to go from:

aList = [ [1,2,3,4,3,2], [2,3,4,5,4,3], [2,1,2,3,4,3] ] 

here:

 new_aList = [ [2,3,4,3,2,1], [3,4,5,4,3,2], [3,4,3,2,1,2] ] 

I get access to each list, but I get a block as to how I would change the position of the values ​​of the nested lists.

Thanks for any help!

+4
source share
4 answers

Use list comprehension to get new items, and you don't have to assign slice to replace existing items in the list.

 new_aList = [list(reversed(x)) for x in aList] aList[:] = [list(reversed(x)) for x in aList] 
+8
source

You can change each item as follows

 >>> aList = [ ... [1,2,3,4,3,2], ... [2,3,4,5,4,3], ... [2,1,2,3,4,3] ... ] >>> aList[0].reverse() >>> aList[1].reverse() >>> aList[2].reverse() >>> aList [[2, 3, 4, 3, 2, 1], [3, 4, 5, 4, 3, 2], [3, 4, 3, 2, 1, 2]] 

But in general it is better to use a loop, since aList can have many elements

 >>> aList = [ ... [1,2,3,4,3,2], ... [2,3,4,5,4,3], ... [2,1,2,3,4,3] ... ] >>> for item in aList: ... item.reverse() ... >>> aList [[2, 3, 4, 3, 2, 1], [3, 4, 5, 4, 3, 2], [3, 4, 3, 2, 1, 2]] 

Both of these methods will modify the aList in place, so the unmodified version will be destroyed. Here's how you can create a new list and leave aList unchanged

 >>> aList = [ ... [1,2,3,4,3,2], ... [2,3,4,5,4,3], ... [2,1,2,3,4,3] ... ] >>> new_aList = [] >>> for item in aList: ... new_aList.append(list(reversed(item))) ... >>> new_aList [[2, 3, 4, 3, 2, 1], [3, 4, 5, 4, 3, 2], [3, 4, 3, 2, 1, 2]] 

Another way to cross out the list is to use this advanced trick. -1 means step through the list with step -1 i.e. in the opposite direction.

 >>> new_aList = [] >>> for item in aList: ... new_aList.append(item[::-1]) ... >>> new_aList [[2, 3, 4, 3, 2, 1], [3, 4, 5, 4, 3, 2], [3, 4, 3, 2, 1, 2]] 

Instead of explicitly creating an empty list and adding to it, it is more common to write a cycle like list comprehension

 >>> new_aList = [item[::-1] for item in aList] >>> new_aList [[2, 3, 4, 3, 2, 1], [3, 4, 5, 4, 3, 2], [3, 4, 3, 2, 1, 2]] 
+3
source
 bList = [] for l in aList: l.reverse() bList.append(l) 
+1
source

For more small-scale manipulation of lists, the position of values ​​can be replaced by unpacking tuples (which avoids the use of temporary variables):

 aList[0][1], aList[0][3] = aList[0][3], aList[0][1] 

After this operation, the second and fourth values ​​will be swapped, so aList[0] will look like this:

 [1, 4, 3, 2, 3, 2] 
0
source

All Articles