Found that the control never reaches the inner while loop in this snippet for deleting a duplicate number
numbers=[1,6,6,7]
k=len(numbers)
i=0
j=0
while i in range(k-1):
while j in range(i+1,k):
if numbers[i] == numbers[j]:
numbers.remove(numbers[j])
k-=1
j-=1
j += 1
i += 1
print(numbers)
Your code does not make j
start at i+1
. Instead it starts at zero and never changes. The inner loop never runs because 0
is outside of the range you are testing.
Try this simple change:
i=0
while i < k+1:
j=i+1
while j < k:
if numbers[i] == numbers[j]:
...
The main change is moving the initialization of j
inside the first while
loop, so it updates each time you go through it, and never starts out less than or equal to i
.
The other change I made is much less important. Rather than using i in range(...)
and j in range(...)
for the while
loop conditions, I just did an inequality test. This is exactly the same as what the range
membership test does under the covers, but avoids unnecessary testing for things that can't happen (like j
being too small, now). It also makes the loop look a lot less like a for
loop, which uses for i in range(...)
syntax a lot (with a different meaning).
Another issue you may run into later, with some sets with multiple sets of duplicates is that your code to remove the j
th element probably doesn't do what you intend. The call numbers.remove(numbers[j])
removes the first value equal to numbers[j]
from the list, which is going to be the one at index i
rather than the one at index j
. To delete a list item by index, you want to use del numbers[j]
.
You could remove duplicates from a list in Python by using the dict.fromkeys()
.
numbers=[1,6,6,7]
final_numbers = list(dict.fromkeys(numbers))
print(final_numbers)
In this example, we use the dict.fromkeys()
method to create a dictionary from numbers
variable. We then use list()
to convert our data from a dictionary back to a list. Then, on the final line, we print out our revised list.
Another option is to use set
. Sets
are used to store collections of unique items in Python. Unlike lists
, sets
cannot store duplicate values. We can convert our list to a set to remove duplicated items.
numbers=[1,6,6,7]
final_numbers = list(set(numbers))
print(final_numbers)
It doesn't reach because j
and i
starts at 0 value and in the inner while loop the condition is j in range(i+1, k)
which means range(1, 4)
and 0 in range(1, 4)
would be False
. Anyways, you should avoid using j
and i
as counters and use a for
loop instead.
But the solution is easier and doesn't need to traverse the list, if you wanna remove the duplicate values, you can do as below:
numbers = [1, 6, 6, 7]
print(list(set(numbers)))
The result is: [1, 6, 7]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.