替换嵌套列表python中的项目 [英] replacing items in nested lists python

查看:141
本文介绍了替换嵌套列表python中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图制作一个列表的重复列表,并将重复列表的嵌套列表中的一个元素更改为另一个元素,但是遇到了一些麻烦. 我如何制作重复列表:

I am trying to make a duplicate list of lists and change one element to another within the nested lists of the duplicate list but am having some trouble. How I made the duplicate list:

order = [['yhjK', 'F'], 'gap', ['bcsA', 'F'], ['bcsB', 'F'], ['bcsZ', 'F'], 'gap', ['yhjK', 'R']]
#order_1 = list(order) #this makes the duplicate list as well
order_1 = []
for x in order:
    order_1.append(x)

我如何更改元素:

for item in order_1:
    for n,i in enumerate(item):
            if i=='R':
                    item[n]='F'
            if i=='F':
                    item[n]='R'

我想用"R"替换所有的"F",反之亦然.这样就完成了,但是原始列表的顺序"也被更改了.我只希望更改第二个列表,但无法弄清楚我的代码有什么问题.

I want to replace all the 'F' with 'R' and vice versa. This accomplishes that but the original list 'order' is changed as well. I only want the second list to be changed and can't figure out what is the problem with my code.

我得到的是

order = [['yhjK', 'R'], 'gap', ['bcsA', 'R'], ['bcsB', 'R'], ['bcsZ', 'R'], 'gap', ['yhjK', 'F']]
order_1 = [['yhjK', 'R'], 'gap', ['bcsA', 'R'], ['bcsB', 'R'], ['bcsZ', 'R'], 'gap', ['yhjK', 'F']]

我想要什么:

order = [['yhjK', 'F'], 'gap', ['bcsA', 'F'], ['bcsB', 'F'], ['bcsZ', 'F'], 'gap', ['yhjK', 'R']]
order_1 = [['yhjK', 'R'], 'gap', ['bcsA', 'R'], ['bcsB', 'R'], ['bcsZ', 'R'], 'gap', ['yhjK', 'F']]

谢谢大家!

推荐答案

您在这里所做的只是列表的浅表副本,因此,当您更改副本时,原始副本也会随之更改.您需要的是 deepcopy

What you're doing here is a shallow copy of the list, so when you change the copy, the original changes as well. What you need is deepcopy

import copy
order = [['yhjK', 'F'], 'gap', ['bcsA', 'F'], ['bcsB', 'F'], ['bcsZ', 'F'], 
'gap', ['yhjK', 'R']]
order_1 = copy.deepcopy(order)

# Now changing order_1 will not change order
order_1[1] = ['TEST LIST']
print order[1] # Prints 'gap'
print order_1[1] # Prints '['TEST LIST']

这篇关于替换嵌套列表python中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆