Skip to content
Advertisement

Compare each element of a list in existing order with elements of a second list in order as long as items in lists are equal

Compare each element of a list in existing order with elements of a second list in existing order as long as items in lists are equal. Stop if they’re not equal and give me as result the index and name of the last match.

I thought it’s straightforward with a while loop but it seems like this has to be approached with a for-loop.

My List one I want to compare: nk_script_file_path

['P:', 'Projects', '2019_projects', '1910_My_Project', '01_Production_IN', '01_OFX', '01_Comp', '00_Nuke', 'relink_test_v001.nk']

My second list I want to compare it to: node_filepath

['P:', 'Projects', '2019_projects', '1910_My_Project', '02_Production_OUT', '01_OFX', '01_Comp', '00_Nuke', '040_ALY', '040_ALY_040_HROTERRORBLADE', '040_ALY_040_HROTERRORBLADE_prev_Gamma22_apcs_mov', '040_ALY_040_HROTERRORBLADE_prev_v14_Gamma22_apcs.mov']

What I’ve tried

nk_script_file_path = r"P:/Projects/2019_projects/1910_My_Project/01_Production_IN/01_OFX/01_Comp/00_SO/relink_test_v001.nk".split("/")
node_filepath = r"P:/Projects/2019_projects/1910_My_Project/02_Production_OUT/01_OFX/01_Comp/00_S=/040_ALY/040_ALY_040_HROTERRORBLADE/040_ALY_040_HROTERRORBLADE_prev_Gamma22_apcs_mov/040_ALY_040_HROTERRORBLADE_prev_v14_Gamma22_apcs.mov".split("/")

# Compare file paths
path_object = 0
while nk_script_file_path in node_filepath:
    path_object += 1
print path_object
print node_filepath[path_object]

Result I’m looking for:

"3"

or

"1910_My_Project"

Advertisement

Answer

You can use zip() with enumerate() to find first index where’s difference. In this example if no difference is found, value of i is equal to -1:

lst1 = ['P:', 'Projects', '2019_projects', '1910_My_Project', '01_Production_IN', '01_OFX', '01_Comp', '00_Nuke', 'relink_test_v001.nk']
lst2 = ['P:', 'Projects', '2019_projects', '1910_My_Project', '02_Production_OUT', '01_OFX', '01_Comp', '00_Nuke', '040_ALY', '040_ALY_040_HROTERRORBLADE', '040_ALY_040_HROTERRORBLADE_prev_Gamma22_apcs_mov', '040_ALY_040_HROTERRORBLADE_prev_v14_Gamma22_apcs.mov']


for i, (a, b) in enumerate(zip(lst1, lst2)):
    if a != b:
        break
else:
    i = -1

print('First difference is at index:', i)

Prints:

First difference is at index: 4
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement