我有以下方法:
def instances(candidate, candidates):
count = candidates.count(candidate)
# Removing candidate from candidates. #
list(filter(candidate.__ne__, candidates))
return {candidate: count}
其预期目的是查找列表中某个元素的实例数,从列表中删除这些实例,然后返回表示该元素及其实例数的 Key:Value
对.
因此,如果我创建一个列表并调用该函数,它应该执行以下操作:
>>> someList = [1, 1, 1, 2, 3]
>>> print(instances(1, someList))
{1: 3}
>>> print(someList)
[2, 3]
但是,对于最后一行,我得到的是:
>>> print(someList)
[1, 1, 1, 2, 3]
行 list(filter(candidate.__ne__, Candidates))
返回我想要的正确列表,但它似乎只存在于函数的范围内。如果我修改此行以改为读取 candidates = list(filter(candidate.__ne__, Candidates))
,由于某种原因 candidates
被解释为范围内的局部变量的函数。我不能简单地返回列表过滤器,因为我需要返回程序的另一部分的 Key:Value
对。
我觉得很奇怪,candidates
在这一行中被解释为局部变量,而就在其上方,对 candidates
的引用被解释为功能。
Can someone please help me understand why this is happening? And if possible, suggest a solution consistent with the intended purpose? Thanks!
最佳答案
I find it really strange that candidates is interpreted as a local variable in this line, whereas just above it, the reference to candidates is interpreted as a parameter of the function.
Python doesn't have references 。它有变量。 foo = bar
表示“使变量 foo
指向 bar
所指向的任何位置。”重新分配变量只是重新定位指针。它不允许您更改指向给定值的“其他”变量。使用相同的方法传递参数:创建一个指向对象的新指针。因此没有对 three star programming 的直接支持
就地修改列表是通过切片语法完成的。你可以这样做:
candidates[:] = filter(candidate.__ne__, candidates)
关于Python - 为什么我的列表没有在此方法的范围之外进行修改?我如何修改我的代码,使其成为这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30564818/