Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么此python代码不替换已删除的列表元素?_Python_List - Fatal编程技术网

为什么此python代码不替换已删除的列表元素?

为什么此python代码不替换已删除的列表元素?,python,list,Python,List,这是我的密码: for each in range(0, number_of_trials): temp_list = source_list for i in range(10): x = random.randrange(0, len(temp_list)) board[i] = temp_list[x] del temp_list[x] 正如预期的那样,此代码正在从临时列表中删除每个元素。但每次运行初始for循环时,都不会重置temp_列表,而是将其设置回

这是我的密码:

for each in range(0, number_of_trials):
  temp_list = source_list
  for i in range(10):
    x = random.randrange(0, len(temp_list))
    board[i] = temp_list[x]
    del temp_list[x]

正如预期的那样,此代码正在从临时列表中删除每个元素。但每次运行初始for循环时,都不会重置temp_列表,而是将其设置回source_列表。因此,temp_列表中的每次删除都是永久性的,在for循环的后续每次迭代中都会持续。如何避免这种情况并使临时列表每次“重置”回其初始状态?

语句
temp\u list=source\u list
不会创建新列表。它为现有列表提供了一个新名称
temp\u list
。无论您使用什么名称访问列表,通过一个名称所做的任何更改都将通过另一个名称可见

相反,您需要复制列表,如下所示:

temp_list = source_list[:]
temp_list = source_list[:]

这将创建一个新列表,该列表以与
source\u list
相同的内容开头。现在,您可以在不影响原始列表的情况下更改新列表。

复制列表元素而不是列表引用

基本上,当您使用“=”时,两个变量都指向同一个对象。要复制,请使用
复制
模块。

这是因为:

temp_list = source_list # Doesn't copies the list, but adds the reference.
因此,每次迭代只刷新引用

要复制列表,可以使用技巧
[:]
。这将执行列表切片而不进行任何切片,并生成与被切片的列表完全相同的新列表

所以,

for each in range(0, number_of_trials):
  temp_list = source_list[:]                # Changed
  for i in range(10):
    x = random.randrange(0, len(temp_list))
    board[i] = temp_list[x]
    del temp_list[x]
这应按预期工作。:)

for each in range(0, number_of_trials):
  temp_list = source_list[:]                # Changed
  for i in range(10):
    x = random.randrange(0, len(temp_list))
    board[i] = temp_list[x]
    del temp_list[x]