【问题标题】:Using list as operand使用列表作为操作数
【发布时间】:2018-04-15 23:36:07
【问题描述】:

将列表传递给函数时遇到问题。它似乎对列表变量有全局影响,但我没有在我的函数中将它声明为全局。谁能告诉我发生了什么以及如何解决它?

def a_Minus_b(a,b):
    for i in range(len(b)):
        print("a= ", a)
        if b[i] in a:
            a.remove(b[i])
    return a

x = [1,2,3,4]
a_Minus_b(x,x)
a=  [1, 2, 3, 4]
a=  [2, 3, 4]
a=  [2, 4]

错误:

Traceback (most recent call last):
  File "<pyshell#115>", line 1, in <module>
    a_Minus_b(x,x)
  File "<pyshell#112>", line 4, in a_Minus_b
    if b[i] in a:
IndexError: list index out of range

【问题讨论】:

  • 请看:youtube.com/watch?v=_AEJHKGk9ns,值得花时间。
  • 不要按索引循环。 for i in range(len(iterable)): iterable[i] 是 python 中的反模式。就做for value in iterable
  • 虽然我强烈推荐完整的视频,但处理函数的部分从15:50开始
  • 容器,如lists,在 Python 中通过引用有效地传递,所以你的函数会改变它传递的那个。

标签: python python-3.x list global operand


【解决方案1】:

如果参数本身是可变的并且 python 列表是可变的,那么 Python 函数可以改变它们的参数。

如果你想让你的功能没有副作用,请先复制数据。

def a_minus_b(a, b):
    a = list(a) # makes a copy and assigns the copy to a new *local* variable
    for val in b:
        print("a = ", a)
        if val in a:
            a.remove(val)
    return a

而不是

a = list(a)

您可以使用以下任何一种:

from copy import copy, deepcopy


a = a[:]         # copies only the references in the list
a = a.copy()     # copies only the references in the list
a = copy(a)      # copies only the references in the list
a = deepcopy(a)  # creates copies also of the items in the list

另外,你正在做的是内置在 python 中,它是 filter 函数。 它接受一个可迭代对象和一个函数,并仅返回函数计算结果为True 的可迭代对象的元素。

print(list(filter(a, lambda elem: elem in b))

filter 返回一个迭代器,要将其转换为列表,请在其上调用list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    相关资源
    最近更新 更多