notice the iteration in the mutable sequences including list. In the function we want to remove the elements both in L1 and L2, however, the output is [2, 3, 4]. why? If we want to get the expected result [3,4], how to modify the program?
时间: 2024-03-08 11:50:08 浏览: 49
cordic.rar_paper_polar_sin vhdl_sin computation_the arctan vhdl
The reason for the unexpected output is due to the fact that you are iterating over `L1` and modifying it at the same time. This can lead to unexpected results since removing an element from the list while iterating over it can change the index of the subsequent elements in the list. In this case, when the function removes `1` from `L1`, the index of `2` gets shifted to the 0th position. However, the iteration continues from the 1st position, causing `2` to be skipped over.
To get the expected result of `[3,4]`, you can create a new list to store the elements that are not in `L2`, instead of modifying `L1` directly. Here is an example implementation of the modified function:
```
def func(L1, L2):
new_list = []
for e in L1:
if e not in L2:
new_list.append(e)
return new_list
L1 = [1, 2, 3, 4]
L2 = [1, 2, 20, 30]
new_list = func(L1, L2)
print(new_list)
```
This will output `[3, 4]` as expected.
阅读全文