Convert string to list without elements being individual characters?
<p>Suppose I have a function called <code>support</code> that counts the number of times passed items occur in elements in a list:</p>

<pre><code>&gt;&gt;&gt; rows = ['candy apple banana cookie', 'candy apple banana', 'candy', 'apple', 'apple banana candy', 'candy apple', 'banana']

&gt;&gt;&gt; def support(item, rows):
        return float(sum([1 for row in rows if item in row]))

&gt;&gt;&gt; print(support('apple', rows))
5.0
</code></pre>

<p>That works well, but eventually I'll need to measure how frequently <strong>two</strong> items occur together in the data. I could define something like this:</p>

<pre><code>&gt;&gt;&gt; def joint_support(items, rows):
        return float(sum([1 for row in rows if all(item in row.split() for item in items)]))
</code></pre>

<p>I'd rather not define two functions that effectively do the same thing. Whether the user passes one or two elements in <code>items</code>, I'd like for the function to count the occurrence of those items, either jointly or separately, in the data. Without using an <code>if</code> statement to measure the length of <code>items</code> (i.e. using a list comprehension), how can I make sure that, if the <code>items</code> parameter is just one string, that the function does not search for joint occurrence of each individual letter?</p>

<p>This is what I have so far:</p>

<pre><code>&gt;&gt;&gt; def master_support(items, rows):
return float(sum([1 for row in rows if all(item in row.split() for item in items if type(items) is not str) else 1 if items in row.split()]))
</code></pre>

<p>Effectively, I think I'm asking how I can automatically convert <code>str</code> to <code>list</code> without the elements of the list being individual characters.</p>

<p>If you are looking for only checking whether all the items exist in the list, you can use <code>set</code> and subtract it.</p>

<pre><code>def joint_support(item, rows):
    if isinstance(item, str):
        item = (item,)
    return float(sum[1 for row in rows if not set(item)-set(row.split(" "))])
</code></pre>

python string