Reputation: 254
I have an array of files that have been added/removed/changed/renamed from git in the form of: [['added',file_1_path],['changed',file_2_path], etc]
And I have a list of file paths that I want to compare.
if the file path in the list is the same as the file path of the array it should do something. If it's not in the whole array, BUT if it's in the list and not in the array I should do something else. Does anyone know how I can solve this problem?
for file_path in file_paths:
for file_in_array in file_paths_array:
if file_in_array[-1] == file_path :
print('do something')
if file_path not in file_paths_array: # I don't know what to do here and this is not correct.
print('do something else')
Upvotes: 1
Views: 139
Reputation: 17352
The list is not the best structure for this taks, because it must be searched again and again.
First convert it to a dict:
file_path_map = {path: data for data, path in file_paths_array}
Then you can access the git's data easily:
for file_path in file_paths:
if file_path in file_path_map:
print('do something')
else:
print('do something else')
If you are interested in the git's data:
for file_path in file_paths:
try:
info = file_path_map[file_path]
except KeyError:
print('do something else')
else:
print('do something with file_path and info')
UPDATE: this assumes that one filepath can be either added or changed or deleted, i.e. it appears only once in the list. If it is not the case, the code must be modified.
Upvotes: 1
Reputation: 51934
The set of files in the file_paths_array
is:
file_set = {x[-1] for x in file_paths_array}
So with that you can do your logic for excluded files:
[...]
elif file_path not in file_set:
print('do something else')
From your example:
file_set = {x[-1] for x in file_paths_array}
for file_path in file_paths:
for file_in_array in file_paths_array:
if file_in_array[-1] == file_path:
print('do something')
elif file_path not in file_set:
print('do something else')
Upvotes: 3