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
JavaScript
x
2
1
['P:', 'Projects', '2019_projects', '1910_My_Project', '01_Production_IN', '01_OFX', '01_Comp', '00_Nuke', 'relink_test_v001.nk']
2
My second list I want to compare it to: node_filepath
JavaScript
1
2
1
['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']
2
What I’ve tried
JavaScript
1
10
10
1
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("/")
2
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("/")
3
4
# Compare file paths
5
path_object = 0
6
while nk_script_file_path in node_filepath:
7
path_object += 1
8
print path_object
9
print node_filepath[path_object]
10
Result I’m looking for:
JavaScript
1
2
1
"3"
2
or
JavaScript
1
2
1
"1910_My_Project"
2
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
:
JavaScript
1
12
12
1
lst1 = ['P:', 'Projects', '2019_projects', '1910_My_Project', '01_Production_IN', '01_OFX', '01_Comp', '00_Nuke', 'relink_test_v001.nk']
2
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']
3
4
5
for i, (a, b) in enumerate(zip(lst1, lst2)):
6
if a != b:
7
break
8
else:
9
i = -1
10
11
print('First difference is at index:', i)
12
Prints:
JavaScript
1
2
1
First difference is at index: 4
2