문제

can some one please explain to me how I could go about converting a set to an int, its homework

when i need to compare the length of the set to the length of a list or something else?

lst = []
oldset =set()
word_set = {}


    while True:
    inp = input('Enter text: ')

    if inp == '':
        print('Finished')
        break

    lst = inp.split()
    for word in lst:
        oldset.add(word)
        oldset = len(oldset)# im sure that this line is my error it tells me to remove .add but i need that

    if word_count < len(word_set):
        word_count[word] = len(word_set.keys())
    print(word,word_count)

the error message i am receiving is

Traceback (most recent call last):                                                                                                                                         
  File "./input_counter.py", line 17, in <module>                                                                                                                          
    oldset.add(word)                                                                                                                                                       
AttributeError: 'int' object has no attribute 'add'
도움이 되었습니까?

해결책

I'm not sure what you're trying to accomplish with this code:

for word in lst:
    oldset.add(word)
    oldset = len(oldset)

But what you are actually accomplishing is as follows: you loop through all the words in lst, and for each word, you try to add the word to oldset, and then you demolish oldset and replace it with an int -- the length of oldset. This obviously only works once, because after you do it once, oldset is no longer a set, but is now an int.

Understand that a set is a container -- it contains many other things -- while an int is simply a value -- it's just a number. What are you trying to do here? Tell us more...

다른 팁

Where s is your set, do len(s). This will return the number of elements in the set.

Please don't refer to this as "converting a set to an int". That's not what you're doing - you're getting the cardinality of the set, and it's not a "conversion" because the int you get isn't some alternate representation of the original, it's a number which holds a property of the original.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top