[英]How do I properly initialize a set in Python?
我最初使用destinations={"x",}
定义了一个集合。 然后我尝试使用destinations=destinations.discard("x")
删除一些东西。 但是,当我尝试运行它时,终端AttributeError: 'NoneType' object has no attribute 'discard'
。 好像还不是一套。 在初始化它时,我在大括号中包含了一个逗号,至少它应该是一个字符串。 我究竟做错了什么?
Quamrana 的评论回答了您问题的本质,但要将其分解:
destinations={"x","y",} #"y" added for the sake of demonstration
destinations = destinations.discard("x")
print(destinations) # Output = '' i.e. no output
如果您看到type(destinations)
,它将 output 作为<class 'NoneType'>
这是因为丢弃(类似于许多其他方法)返回 NoneType object。 (对于 list.append() 等其他方法也是如此。但是,请注意,并非所有方法都如此。例如 dict.pop(key) 返回非 NoneType Object。)
现在为正确的方法做到这一点:
destinations={"x","y",} #"y" added for the sake of demonstration
destinations.discard("x")
print(destinations) # Output: {'y'}
如果您看到type(destinations)
,它将 output 作为<class 'set'>
有趣的是,如果您要重新分配变量,您的原始集合仍然会受到影响。
destinations = {"x","y"}
new_set = destinations
new_set.discard('x')
print(new_set) # output = {'y'}
print(destinations) # output = {'y'}
由于您正在学习 CS50,我认为 David 在教授列表时会涉及到这一点:学习愉快 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.