Nobi
Nobi

Reputation: 1109

Comparing list of list of list

I want to compare two list of list of lists and replace items in the first list that is different in the second list. What I want is that since List1[0][2][0:3] is the same as List2[0][2][0:3], but their last elements are different, replace List1[0][2][-1] with List2[0][2][-1]. I have worked with list of lists and many examples on SO such as this deal with that but I don't know how to go about a comparison for a list of list of lists also, both lists are not always uniform in the real data set.

List1

[[['192', '177', '4', '749'], ['192', '177', '5', '749'], ['192', '177', '6', '999999']], [['192', '178', '1', '999999'], ['192', '178', '2', '999999'], ['192', '178', '3', '999999'], ['192', '178', '4', '999999'], ['192', '178', '5', '1511'], ['192', '178', '6', '999999']]]

List2

[[['192', '177', '4', '749'], ['192', '177', '5', '749'], ['192', '177', '6', '222222']], [['192', '178', '1', '222222'], ['192', '178', '2', '222222'], ['192', '178', '3', '222222'], ['192', '178', '4', '222222'], ['192', '178', '5', '1511'], ['192', '178', '6', '999999']]]

Upvotes: 1

Views: 98

Answers (1)

Jacob G.
Jacob G.

Reputation: 29680

Because you specified that you want to replace values in the first list with values that differ in the second list, I will assume that the size of the second list and its nested lists can only be equal to or larger than the size of the first list and its nested lists.

With this assumption, we can simply set each nested list in list1 to its respective sliced nested list in list2, without the need to compare any values.

list1 = [[['192', '177', '4', '749'], ['192', '177', '5', '749'], ['192', '177', '6', '999999']], [['192', '178', '1', '999999'], ['192', '178', '2', '999999'], ['192', '178', '3', '999999'], ['192', '178', '4', '999999'], ['192', '178', '5', '1511'], ['192', '178', '6', '999999']]]

list2 = [[['192', '177', '4', '749'], ['192', '177', '5', '749'], ['192', '177', '6', '222222']], [['192', '178', '1', '222222'], ['192', '178', '2', '222222'], ['192', '178', '3', '222222'], ['192', '178', '4', '222222'], ['192', '178', '5', '1511'], ['192', '178', '6', '999999']]]

list = []

for i in range(len(list2)):
    for j in range(len(list2[i])):
        list.append(list2[i][j][:len(list1[i][j])])

I'll see if I can find a good list comprehension for this.

Upvotes: 1

Related Questions