-7

有人可以向我解释一下如何将集合转换为int,它的作业

当我需要将集合的长度与列表的长度或其他内容进行比较时?

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)

我收到的错误消息是

Traceback (most recent call last):                                                                                                                                         
  File "./input_counter.py", line 17, in <module>                                                                                                                          
    oldset.add(word)                                                                                                                                                       
AttributeError: 'int' object has no attribute 'add'
4

2 回答 2

5

你的套装在哪里s,做len(s)。这将返回集合中元素的数量。

请不要将此称为“将集合转换为 int”。那不是你在做的——你得到了集合的基数,这不是“转换”,因为你得到的 int 不是原始的一些替代表示,它是一个拥有原始属性的数字.

于 2012-02-06T01:56:33.263 回答
3

我不确定你想用这段代码完成什么:

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

但是你实际完成的是如下:你循环遍历 中的所有单词lst,并且对于每个单词,你尝试将单词添加到oldset,然后你将其删除oldset并替换为int- 的长度oldset。这显然只有效一次,因为在您执行一次之后,oldset不再是 a set,而是现在是 a int

了解 aset是一个容器——它包含许多其他东西——而 anint只是一个值——它只是一个数字。你想在这里做什么?跟我们多说些...

于 2012-02-06T02:18:06.557 回答