如何在 Python 中正确初始化集合?
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)
,它将输出为<class 'NoneType'>
那是因为丢弃(类似于许多其他方法)returns 一个 NoneType 对象。
(其他方法如 list.append() 也是如此。但是请注意,并非所有方法都如此。例如 dict.pop(key) returns a非 NoneType 对象。)
现在了解正确的方法:
destinations={"x","y",} #"y" added for the sake of demonstration
destinations.discard("x")
print(destinations) # Output: {'y'}
如果你看到type(destinations)
,它会输出为<class 'set'>
有趣的是,如果您要重新分配变量,您的原始设置仍会受到影响。
destinations = {"x","y"}
new_set = destinations
new_set.discard('x')
print(new_set) # output = {'y'}
print(destinations) # output = {'y'}
由于您正在学习 CS50,我认为 David 会在讲授列表的时候讲到这一点!祝您学习愉快:)
我最初使用 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)
,它将输出为<class 'NoneType'>
那是因为丢弃(类似于许多其他方法)returns 一个 NoneType 对象。 (其他方法如 list.append() 也是如此。但是请注意,并非所有方法都如此。例如 dict.pop(key) returns a非 NoneType 对象。)
现在了解正确的方法:
destinations={"x","y",} #"y" added for the sake of demonstration
destinations.discard("x")
print(destinations) # Output: {'y'}
如果你看到type(destinations)
,它会输出为<class 'set'>
有趣的是,如果您要重新分配变量,您的原始设置仍会受到影响。
destinations = {"x","y"}
new_set = destinations
new_set.discard('x')
print(new_set) # output = {'y'}
print(destinations) # output = {'y'}
由于您正在学习 CS50,我认为 David 会在讲授列表的时候讲到这一点!祝您学习愉快:)