Python 如何将集合转换为整数

-7 投票
2 回答
22189 浏览
提问于 2025-04-17 12:23

有人能告诉我怎么把一个集合转换成整数吗?这是我的作业。

我需要把集合的长度和列表或其他东西的长度进行比较时,该怎么做呢?

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'

2 个回答

5

这里的 s 是你的集合,使用 len(s) 这个命令。它会告诉你集合里有多少个元素。

请不要把这称作“把集合转换成一个整数”。其实你并不是在转换,而是在获取集合的“基数”,也就是元素的数量。这不是一种“转换”,因为你得到的整数并不是原来集合的另一种“表现形式”,而是一个表示原集合特性的数字。

3

我不太明白你想用这段代码实现什么:

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

但实际上你得到的结果是这样的:你在遍历 lst 中的所有单词,对于每个单词,你试图把这个单词添加到 oldset 中,然后你又把 oldset 拆掉,换成一个 int —— 也就是 oldset 的长度。显然,这样只会成功一次,因为你做完一次后,oldset 就不再是一个 set 了,而变成了一个 int

要明白,set 是一个 容器 —— 它可以装很多其他东西,而 int 只是一个值 —— 就是一个数字。你想在这里做什么呢?多告诉我们一些吧……

撰写回答