python - AttributeError when converting a list of strings to a list of sets -
i'm trying write function add results of loop set, taking list , using set() take out duplicate letters in strings within list.
however; whenever run code, hit error says .add isn't dict definition.
def make_itemsets(l): item_set = {} item in l: item_set.add(set(item)) return item_set 2 item_set = {} 3 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 trying list (l = ["apples","bananas","carrot"] run through function i've created return new list [{'a','p','l','e','s'},{'b','a','n','s'} etc. etc.]
it seems want list of sets instead. how about:
def make_itemsets(l): items = [] item in l: items.append(set(item)) return items note return statement outside loop. shorter version using list comprehension entail:
def make_itemsets(l): return [set(item) item in l] or, shorter version using map:
def make_itemsets(l): return list(map(set, l)) you can drop list(...) if you're on python2. calling 1 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 create empty set, you'll need
item_set = set() {} happens create empty dict. have @ disassembled byte code:
>>> dis.dis("{}") 1 0 build_map 0 3 return_value the 0 build_map stmt creates map (aka, dictionary). contrast with:
>>> dis.dis("set()") 1 0 load_name 0 (set) 3 call_function 0 (0 positional, 0 keyword pair) 6 return_value
Comments
Post a Comment