replacing items in nested lists python

前端 未结 5 1405
死守一世寂寞
死守一世寂寞 2021-01-16 07:04

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 dup

5条回答
  •  孤独总比滥情好
    2021-01-16 07:48

    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']
    

提交回复
热议问题