Novice question here.
I’m working on finding every single combination of various string elements, and then want to place them into a list.
import itertools
mydata = [ ]
main = [["car insurance", "auto insurance"], ["insurance"], ["cheap", "budget"],
["low cost"], ["quote", "quotes"], ["rate", "rates"], ["comparison"]]
def twofunc(one, two):
for a, b in itertools.product(main[one], main[two]):
print a, b
def threefunc(one, two, three):
for a, b, c in itertools.product(main[one], main[two], main[three]):
print a, b, c
twofunc(2, 0) #extremely inefficient to just run these functions over and over. alternative?
twofunc(3, 0)
twofunc(0, 4)
twofunc(0, 5)
twofunc(0, 6)
threefunc(2, 0, 4)
threefunc(3, 0, 4)
threefunc(2, 0, 5)
threefunc(3, 0, 5)
threefunc(2, 0, 6)
threefunc(3, 0, 6)
The above code just prints out each permutation, but doesn’t append the values to the list. I’ve tried various variations on the append method and still have no luck.
Can anyone help me with placing these values into the mydata list. I assume that each string will have to be a seperate list, so it will end up being a list of lists. It should look like the following, but I’ll also need some way to include “tags” in the future, or just values for if the string contains a value.
[["cheap car insurance"],
["cheap auto insurance"],
["budget car insurance"],
["budget auto insurance"],
["low cost car insurance"],
["low cost auto insurance"],
...
so, eventually, will end up: 1 means that the strings contains the word car/cheap, and 0 means that it doesn’t. The reason I mention this is just to inquire if a list is the proper data structure for this task.
car cheap
cheap car insurance 1 1
cheap auto insurance 0 1
budget car insurance 1 0
budget auto insurance 0 0
Can anyone help.
I’ve completed this task in R, which is pretty amenable to this task, and just wanted to reproduce it in Python.
To get the return values of twofunc and threefunc into a list, you can change the return statements so that lists are returned. Then append the result to mydata. An example follows for twofunc:
That said, I’m not familiar with R, so obviously don’t know what data structure you might be using there. For your stated goal, keeping this in a list might get complicated. However, creating a simple class to do this shouldn’t be too difficult. You could then have a list made up of instantiations of this class.