replacing items in nested lists python

前端 未结 5 1361
死守一世寂寞
死守一世寂寞 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:37
    import copy
    order_1 = copy.deepcopy(order)
    

    Python by default only copies references to mutable values, so changing them in one place results in them being changed everywhere. Creating a deep copy means the two instances are completely independent.

    0 讨论(0)
  • 2021-01-16 07:38

    It seems that, as with many other languages, arrays are no more than constants (not even actual pointers although that might be different in python). Rather, The address of the first element of the array is constant. This means that if you would directly copy the array, you would only copy the address of the first element.

    From your question, I understand that you want a deep copy. That means that, you also need to copy the contents of you nested arrays. You can use copy.deepcopy(x) to make a deepcopy of the array.

    Check out the copy module for more in-depth information.

    0 讨论(0)
  • 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']
    
    0 讨论(0)
  • 2021-01-16 07:49
    L = [['F' if x == 'R' else 'R' if x == 'F' else x for x in row] for row in order]
    
    0 讨论(0)
  • 2021-01-16 07:54
    order_1 = []
    for item in order:
        temp = []
        for i in item:
            if i=="F":
                temp.append("R")
            elif i=="R"
                temp.append("F")
            else:
                temp.append(i)
        order_1.append(temp)
    
    0 讨论(0)
提交回复
热议问题