Creating directories from two lists - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Creating directories from two lists (/thread-11091.html) |
Creating directories from two lists - QueenSveta - Jun-22-2018 I have the following namedtuple and List from collections import namedtuple firefoxprofile = namedtuple("Profile", ["Name", "Path", "isRelative", "Default"]) jb = firefoxprofile(Name='Jason', Path='Profiles/er5rtak4.Jason', isRelative='1', Default=None) sr = firefoxprofile(Name='Sarah', Path='Profiles/23mvfqcj.Sarah', isRelative='1', Default=None) files = ["places.sqlite","key4.db", "logins.json"] firefoxlisttuple = [] firefoxlisttuple.append(jb) firefoxlisttuple.append(sr)I'm using a nested for loop to create the paths to each of the files in the files List. Example: for profile in firefoxlisttuple: for file in files: print("{0}\{1}".format(profile.Path,file))Output: Profiles/er5rtak4.Jason/places.sqlite Profiles/er5rtak4.Jason/key4.db Profiles/er5rtak4.Jason/logins.json Profiles/23mvfqcj.Sarah/places.sqlite Profiles/23mvfqcj.Sarah/key4.db Profiles/23mvfqcj.Sarah/logins.jsonI'm aware that a nested for loop isn't a good idea in terms of preformace. What should I do instead to achieve the same output? RE: Creating directories from two lists - gontajones - Jun-22-2018 In this case, I think you can use some syntax sugars to "hide" (but not avoid) the for loops. Maybe using product you can get a better performance (test it for large amount of entries). myrange = [ [x for x in firefoxlisttuple], [y for y in files], ] for profile, file in itertools.product(*myrange): print("{0}\{1}".format(profile.Path, file))And if your files array will be the same all the time, you can use direct assignment: for profile in firefoxlisttuple: print("{0}\{1}".format(profile.Path, files[0])) print("{0}\{1}".format(profile.Path, files[1])) print("{0}\{1}".format(profile.Path, files[2]))You'll have to analyse what are the lengths of the arrays and check the performance. RE: Creating directories from two lists - volcano63 - Jun-22-2018 (Jun-22-2018, 02:51 AM)QueenSveta Wrote: ...... Nothing wrong with nested loops. Of course, if you want to create a list - or list of lists - then list comprehension will give a better performance (not that performance is an issue in your case). You could have used itertools.product - as advised by @gontajones, for profile, file in itertools.product(firefoxlisttuple, files): print("{0}\{1}".format(profile.Path,file))but performance-wise it may be even worth (who measures performance when printing ) Questioning yourself is an admirable quality, but in that case you are falling into the trap of "Pythonic" objection to loops - which is a false claim, the choice between loop and comprehension is context-specific. And remember, Premature optimization is the root of all evil
|