简体   繁体   English

如何修改基于另一个列表的元素

[英]How to modify the elements of one list based on another

I have two lists like 我有两个清单

lst1 = ['a', 'b', 'c', 'd', 'e']
lst2 = ['q', 'r', 's']

Now, suppose I generate a mapping from list2 to list1 one like (4, 0, 3) meaning update the 4th element of list1 with the 0th element of list2, update the 0th element of list1 with the 1st element of list2, etc. such that the resulting list looks like 现在,假设我生成了一个从list2到list1的映射,例如(4,0,3),这意味着用list2的第0个元素更新list1的第4个元素,用list2的第一个元素更新list1的第0个元素,以此类推。结果列表看起来像

lst1 = ['r', 'b', 'c', 's', 'q']

How can I do this? 我怎样才能做到这一点?

One way would be to use enumerate : 一种方法是使用enumerate

lst1 = ['a', 'b', 'c', 'd', 'e']
lst2 = ['q', 'r', 's']
mapping = [4, 0, 3]

for lst2_n, lst1_n in enumerate(mapping):
    lst1[lst1_n] = lst2[lst2_n]

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

相关问题 如何以另一个列表中的元素为条件修改一个列表中的元素? - How can I modify elements in one list conditional on the elements in another list? 如何根据另一个列表中的连续元素对一个列表中的项目进行分组? - How to group items in one list based on consecutive elements in another list? Pandas:根据另一列修改一列的列表元素 - Pandas: Modify list elements of a column based on another column 根据另一个列表的元素更改一个列表中的元素 - Change elements in one list based on elements of another list 如何删除基于另一个列表的列表中的元素? - How to delete elements in a list based on another list? 基于另一个列表中的元素重复一个列表中的元素 - Repeat elements in one list based on elements from another 根据python中的另一个列表匹配列表的元素,其中一个列表的元素是另一个列表的子字符串 - match element of a list based on another list in python where elements of one list is the substring of elements of another list 根据另一个布尔列表从一个列表中获取元素 - Get elements from one list based on another boolean list 根据另一个列表中的索引汇总一个列表中的元素 - Summing up elements from one list based on indices in another list 根据另一个列表将一个字符串元素列表分组 - Group one list of string elements based on another list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM