Identifying locations of distinct sublists in Python

Advertisements

I have a list J1 containing many sublists. I am identifying all the distinct sublists and the locations (first and last) at which they occur. I present the current and expected output.

J1 = [[0, 3, 7, 9, 10], [0, 3, 7, 9, 10], [0, 3, 7, 9, 10], [0, 0, 7, 9, 10], [0, 0, 7, 9, 10], [0, 0, 0, 9, 10]]

distinct_sublists = []
sublist_indices = {} 
for i, sublist in enumerate(J1):
 if sublist not in distinct_sublists:
     distinct_sublists.append(sublist)
     sublist_indices[tuple(sublist)] = [i, i]
else:
    sublist_indices[tuple(sublist)][1] = i

num_distinct_sublists = len(distinct_sublists)

first_last_locations = [[indices[0], indices[1]] for indices in sublist_indices.values()]

print("Number of distinct sublists in J1:", num_distinct_sublists)
print("First and last locations of distinct sublists in J1:", first_last_locations)
print("Distinct sublists", distinct_sublists)

The current output is

Number of distinct sublists in J1: 3
First and last locations of distinct sublists in J1: [[0, 0], [3, 3], [5, 5]]
Distinct sublists [[0, 3, 7, 9, 10], [0, 0, 7, 9, 10], [0, 0, 0, 9, 10]]

The expected output is

Number of distinct sublists in J1: 3
First and last locations of distinct sublists in J1: [[0, 2], [3, 4], [5, 5]]
Distinct sublists [[0, 3, 7, 9, 10], [0, 0, 7, 9, 10], [0, 0, 0, 9, 10]]

>Solution :

your code looks perfect except for the indentation, just indent the "else" statement:

for i, sublist in enumerate(J1):
    if sublist not in distinct_sublists:
        distinct_sublists.append(sublist)
        sublist_indices[tuple(sublist)] = [i, i]
    else:
        sublist_indices[tuple(sublist)][1] = i

For each sublist in J1 you want to check if the sublist has already been recorded: if so, update the first/last indices as [i,i], else (i.e. if it’s already been recorded) just update the last index as i.

In Python, indentation really matters, so depending on previous language experience that might be unexpected. Also, in Python, a for loop can have an else of its own:

for i in range(10):
   if i != 5:
      do_something()
   else:        # this else executes if the "if" statement condition is false
      do_something_else()
else:           # this else executes after the "for" loop is completed
   do_yet_another_thing()

Leave a ReplyCancel reply