Say we have two lists of values, list1
and list2
, and tow lists of indices, index1
and index2
. How do we copy elements with position index2
in list2
to elements with position index1
in list1
. In Matlab, for example, we can simply write list1[index1] = list2[index2]
, but strangely this does not seem to work in Python. Also, how do we do this if index1
and/or index2
is a list of booleans?
For example, say list1 = ['a','b','c','d','e']
and list2 = ['A','B','C','D','E']
and index1 = [0,1,3]
and index2 = [1,2,4]
with the result of list1[index1] = list2[index2]
being list1: ['B','C','c','E','e']
.
In the case of boolean, the same output should be achived with index1 = [True,True,False,True,False]
and index2 = [False,True,True,False,True]
.
PS: It is clear how to do this with a for
loop. I am looking for a more "pythonic" way, eg list comprehension. Thank you
PPS: After some experimentation, I defined a class MyList
which inhereted from class Python's list
and modified __getitem__
and __setitem__
to accept lists of integers or booleans. The class definition is given in my post here How to extend list class to accept lists for indecies in Python, eg to use list1[list2] = list3[list4]
You can use a simple for-loop with enumerate
:
list1 = ['a','b','c','d','e']
list2 = ['A','B','C','D','E']
index1 = [0,1,3]
index2 = [1,2,4]
for i, val in enumerate(index1):
list1[val] = list2[index2[i]]
print(list1)
Output:
['B', 'C', 'c', 'E', 'e']
Or alternatively with zip
:
list1 = ['a','b','c','d','e']
list2 = ['A','B','C','D','E']
index1 = [0,1,3]
index2 = [1,2,4]
for a, b in zip(index1, index2):
list1[a] = list2[b]
print(list1)
Output:
['B', 'C', 'c', 'E', 'e']
As far as I can see, the boolean case is a completely different one, and should be asked in a separate question.
Use zip
and combine the elements of the two index lists.
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['A', 'B', 'C', 'D', 'E']
index1 = [0, 1, 3]
index2 = [1, 2, 4]
for i1, i2 in zip(index_1, index_2):
list1[i1] = list2[i2]
print(list1)
list1 = ['a','b','c','d','e']
list2 = ['A','B','C','D','E']
index1 = [0,1,3]
index2 = [1,2,4]
x=0
for i in index1:
list1[i] = list2[index2[x]]
x+=1
print(list1)
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.