简体   繁体   中英

AttributeError when converting a list of strings to a list of sets

I'm trying to write a function to add the results of a loop to a set, basically taking a list and using set() to take out any duplicate letters in the strings within the list.

However; whenever I run the code, I hit an error that says .add isn't a dict definition.

def make_itemsets(L):
    item_set = {}
    for item in L:
        item_set.add(set(item))
        return item_set


      2     item_set = {}
      3     for item in L:
----> 4         item_set.add(set(item))
      5         return item_set
      6 

AttributeError: 'dict' object has no attribute 'add'

Any ideas? I'm basically trying to get this list (L = ["apples","bananas","carrot"] to run through a function I've created to return a new list [{'a','p','l','e','s'},{'b','a','n','s'} etc. etc.]

It seems like you want a list of sets instead. How about:

def make_itemsets(L):
    items = []
    for item in L:
        items.append(set(item))

    return items

Note the return statement outside the loop. A shorter version using a list comprehension would entail:

def make_itemsets(L):
    return [set(item) for item in L]

Or, an even shorter version using a map :

def make_itemsets(L):
    return list(map(set, L))

You can drop the list(...) if you're on python2. Calling any one of these functions returns:

>>> s = make_itemsets(["apples","bananas","carrot"])
>>> s
[{'a', 'e', 'l', 'p', 's'}, {'a', 'b', 'n', 's'}, {'a', 'c', 'o', 'r', 't'}]

For reference, if you're trying to create an empty set, you'll need

item_set = set()

{} happens to create an empty dict . Have a look at the disassembled byte code:

>>> dis.dis("{}")
  1           0 BUILD_MAP                0
              3 RETURN_VALUE

The 0 BUILD_MAP stmt creates a map (aka, dict ionary). Contrast with:

>>> dis.dis("set()")
  1           0 LOAD_NAME                0 (set)
              3 CALL_FUNCTION            0 (0 positional, 0 keyword pair)
              6 RETURN_VALUE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM