一个打印到列表的打印语句会破坏列表吗?

时间:2016-12-21 11:41:51

标签: python

任何人都可以解释一下:

让dict_list成为:

dict_list = [
{'a':1, 'b':3},
{'a':2, 'b':4}
]

案例A(列表被销毁)

然后是以下代码:

1 print('length: ' + str(len(dict_list)))
2 filtered_dict_list = filter(lambda d: d['a'] == 1, dict_list)
3 print('length: ' + str(len(list(filtered_dict_list))))
4 dict_list = list(filtered_dict_list)
5 print('length: ' + str(len(dict_list)))

将打印:

length: 2
length: 1
length: 0

dict_list在代码中永远消失了

案例B(列表未销毁)

通过切换第3和第4行:

1 print('length: ' + str(len(dict_list)))
2 filtered_dict_list = filter(lambda d: d['a'] == 1, dict_list)
3 dict_list = list(filtered_dict_list)
4 print('length: ' + str(len(list(filtered_dict_list))))
5 print('length: ' + str(len(dict_list)))

我们得到:

length: 2
length: 0
length: 1

并且可以继续使用我们过滤的dict_list

1 个答案:

答案 0 :(得分:3)

在Python 3中,Public Sub DeleteElementAt(ByVal ArrIndex As Integer, ByRef myArr As Variant) ' this sub removes a certain element from the array, then it shrinks the size of the array by 1 Dim i As Integer ' move all element back one position For i = ArrIndex + 1 To UBound(myArr) myArr(i - 1) = myArr(i) Next ' shrink the array by one, removing the last one ReDim Preserve myArr(UBound(myArr) - 1) End Sub 返回一个filter()对象,它是一个惰性生成器,并不会像Python 2 filter那样自动生成list对象。在您的代码中,您只需更改首先打印的结果。

filter()

在第二个区块中:

1 print('length: ' + str(len(dict_list)))
2 filtered_dict_list = filter(lambda d: d['a'] == 1, dict_list)
3 print('length: ' + str(len(list(filtered_dict_list)))) # consumes filtered_dict_list
4 dict_list = list(filtered_dict_list) # attempts to consume an exhausted generator, saving an empty list
5 print('length: ' + str(len(dict_list))) # length of that empty list

这不是耗尽发电机的1 print('length: ' + str(len(dict_list))) 2 filtered_dict_list = filter(lambda d: d['a'] == 1, dict_list) 3 dict_list = list(filtered_dict_list) # consume filtered_dict_list, and *save* it 4 print('length: ' + str(len(list(filtered_dict_list)))) # attempts to consume an exhausted generator, result is empty 5 print('length: ' + str(len(dict_list))) # print the *saved* dict_list 电话;这是print()电话。如果您将list()发送至filtered_dict_list而未先将其发送至print(),则会打印list()之类的内容。