【问题标题】:Confused about how set in python returns values对python中的set如何返回值感到困惑
【发布时间】:2017-11-20 06:51:28
【问题描述】:

我有一个代码。

scores = [19.0,19.0,20.0,20.0,21.0,21.0]
new_scores = set(scores)
print new_scores

输出: 设置([19.0, 20.0, 21.0])

我的问题: 为什么在输出前加上“set”这个词。 不设置应该直接返回列表“分数”中的唯一值。另外,如果我使用'list(set(scores))',那么我只得到不带前缀词'set'的唯一值列表的预期输出

【问题讨论】:

  • Why is the word 'set' prefixed to the output. 为什么不呢?您应该向编写__str__ 方法的人询问set
  • set 是一个集合,而不是一个列表。

标签: python list set


【解决方案1】:

set 是 Python 中的一种类型。当你这样做时:

set(some_list)

你没有得到一个列表,你得到一个set。 Python 中的setlist 不同,并且有自己的接口。例如,您不能将append 转换为set。你只能add

>>> my_set = set(['a', 'b'])
>>> my_set.append('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'set' object has no attribute 'append'
>>> my_set.add('a')
>>> print(my_set)
{'a', 'b'}

请注意,当我 add 到集合时,我仍然只有 'a',因为它的表现就像一个集合。

但是:

list(set(['a']))

它现在是一个列表。不再表现得像一个集合,因此:

>>> my_list = list(set(['a']))
>>> my_list.append('a')
>>> print(my_list)
['a', 'a']

请注意,该结构行为类似于list

【讨论】:

  • 没问题,很高兴能帮上忙!
猜你喜欢
  • 2021-04-06
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
相关资源
最近更新 更多