简体   繁体   English

在python中将1个列表中的项目替换为另一个列表中的项目

[英]Replacing items in 1 list to items in another list in python

I'm trying to replace items in 1 list of lists with items from another list of lists. 我试图用另一个列表中的项目替换列表中的1个列表中的项目。

    alist = [[1,2,3], [4,5,6], [7,8,9]]
    blist = [[a,b,c], [d,e,f], [g,h,i]]

Basically, I want to replace the items in alist with it's blist counterpart. 基本上,我想用blist对应项替换alist中的项目。 For example, if someone chose 1 in alist, I want to replace it with the same index from blist which would be a. 例如,如果某人在列表中选择1,我想将其替换为blist中相同的索引(即a)。

    alist = [[a,2,3], [4,5,6], [7,8,9]]

Any suggestions? 有什么建议么?

One way is to loop over both lists together, then loop over each subgroup to replace the matched choice. 一种方法是将两个列表一起循环,然后循环每个子组以替换匹配的选择。

For lockstep iteration, the zip function is your best friend. 对于锁步迭代, zip函数是您最好的朋友。 For transforming lists a list comprehension is a great tool. 对于转换列表, 列表理解是一个很好的工具。 Here's how to use them: 使用方法如下:

>>> alist = [[1,2,3], [4,5,6], [7,8,9]]
>>> blist = [[10,20,30], [40,50,60], [70,80,90]]
>>> choice = 1
>>> alist = [[(bx if ax==choice else ax) for ax, bx in zip(aseq, bseq)] for aseq, bseq in zip(alist, blist)]
>>> alist
[[10, 2, 3], [4, 5, 6], [7, 8, 9]]

What is nice about this approach is that it can do multiple replacements (for example, if alist contains several 1 entries, they all get replaced with their corresponding entries in the blist ). 这种方法的好处是它可以进行多次替换(例如,如果alist包含多个1条目,则它们都将全部替换为blist中的相应条目)。

Another nice feature is that the ax==choice decision can easily be replaced with other predicates (for example, ax in {2, 5, 8} will search for multiple substitution targets in a single pass). 另一个不错的功能是ax==choice决策可以很容易地用其他谓词替换(例如, ax in {2, 5, 8}将在一次遍历中搜索多个替换目标)。 Another example is ax % 2 == 0 which would make blist replacements for any alist value that is even). 另一个示例是ax % 2 == 0 ,它将blist替换为偶数的alist值。

>>> z = [(i, x.index(item)) for i, x in enumerate(alist) if item in x][0]
>>> alist[z[0]][z[1]] = blist[z[0]][z[1]]
>>> alist
[['a', 2, 3], [4, 5, 6], [7, 8, 9]]

See it working online: ideone 看到它在线上工作: ideone

Crude but easily explained: 粗略但容易解释:

blist = [['a','b','c'], ['d','e','f'], ['g','h','i']]
alist = [[1,2,3], [4,5,2], [7,8,9]]
x = 2

for y in xrange(len(alist)):
    if x in alist[y]:
        i = alist[y].index(x)
        alist[y][i] = blist[y][i]

print alist

Output: 输出:

[[1, 'b', 3], [4, 5, 'f'], [7, 8, 9]]

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM