How can I add items to an empty set in python

前端 未结 3 1058
猫巷女王i
猫巷女王i 2021-01-30 04:55

I have the following procedure:

def myProc(invIndex, keyWord):
    D={}
    for i in range(len(keyWord)):
        if keyWord[i] in invIndex.keys():
                      


        
相关标签:
3条回答
  • 2021-01-30 05:20

    D = {} is a dictionary not set.

    >>> d = {}
    >>> type(d)
    <type 'dict'>
    

    Use D = set():

    >>> d = set()
    >>> type(d)
    <type 'set'>
    >>> d.update({1})
    >>> d.add(2)
    >>> d.update([3,3,3])
    >>> d
    set([1, 2, 3])
    
    0 讨论(0)
  • 2021-01-30 05:23

    When you assign a variable to empty curly braces {} eg: new_set = {}, it becomes a dictionary. To create an empty set, assign the variable to a 'set()' ie: new_set = set()

    0 讨论(0)
  • 2021-01-30 05:33
    >>> d = {}
    >>> D = set()
    >>> type(d)
    <type 'dict'>
    >>> type(D)
    <type 'set'>
    

    What you've made is a dictionary and not a Set.

    The update method in dictionary is used to update the new dictionary from a previous one, like so,

    >>> abc = {1: 2}
    >>> d.update(abc)
    >>> d
    {1: 2}
    

    Whereas in sets, it is used to add elements to the set.

    >>> D.update([1, 2])
    >>> D
    set([1, 2])
    
    0 讨论(0)
提交回复
热议问题