i can always change bwtween list if I do not have them in One array...
If I have an array having more than one list
a = [[2,3,4,],[8,14,13],[12,54,98]]
how do I replace a[2]
with a[0]
??
Thanks in Advance
Lists are mutable so you probably want to replace list items, not the lists themselves:
a[2][:] = a[0]
If you want to swap lists rather than replace them then:
a[0], a[2] = a[2], a[0]
For your original post:
a = [[2,3,4,],[8,14,13],[12,54,98]] a[2] = a[0]
then
a
will be:
[[2, 3, 4], [8, 14, 13], [2, 3, 4]]
Update based on comment to sdolan below:
If you want to exchange the two, you could simply do this:
[[12, 54, 98], [8, 14, 13], [2, 3, 4]]
giving
[[12, 54, 98], [8, 14, 13], [2, 3, 4]]
You can just assign it:
>>> a = [[2,3,4,],[8,14,13],[12,54,98]]
>>>
>>> a[2] = list(a[0]) # list() to create a new copy
>>> a
[[2, 3, 4], [8, 14, 13], [2, 3, 4]]
The way you asked this is to just change the array from a = [[2,3,4,],[8,14,13],[12,54,98]]
to a = [[2,3,4,],[8,14,13],[2,3,4,]]
so you can do a[2] = a[0]
but if you want to swap them, you will need something like:
b = a[0]
a[0] = a[2]
a[2] = b
EDIT for shorthand:
a[0], a[2] = a[2], a[0]
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.