I have a solution to erase duplicates from a list. In this solution is used an enumerate.
def myfunc(list_input):
list_output=[]
for num1, num2 in enumerate(list_input):
if num2 not in list_input[0:num1]:
list_output.append(num2)
return list_output
print(myfunc([1,1,2,3])) --> ,[1,2,3,]
However, I do not undersatand in which way we should read the index position for our enumerate.
What is the position for each interaction in list_input[0:num1]
, having in consideration that we have started the for
loop with a num1, num2
?
Enumerate iterates over an iterable (in this cause list_input
), and with each iteration sets the first value (in this case num1
) to the current index, and the second value (in this case num2
) to the value of the iterable at this index.
For example, on first iteration, num1 == 0
as the iteration begins at the zeroeth element, and num2 == 1
as list_input[0] == 1
. list_input[0:num1] == []
so nothing is in it and therefore the value is appended to the outputs.
On second iteration, the index has incremented by one and so num1 == 1
. list_input[0:num1] == [1]
now, and as num2
is in [1]
, the value is not appended to the output list.
The question needs to be elaborated on, and please do fix the formatting. But if I understand correctly, if you want to remove duplicates and have a need for the positioning or index of each element (number) of the non-duplicates you make use of enumerate() and possibly do something like this:
nums = [1,1,3,5,7,9]
newlist = []
for num in nums:
if num not in newlist:
newlist.append(num)
for index, nums in enumerate(newlist):
print("Index positioning: %s and Number at respective index is: %s" % (index,nums))
Output:
Index positioning: 0 and Number at respective index is: 1
Index positioning: 1 and Number at respective index is: 3
Index positioning: 2 and Number at respective index is: 5
Index positioning: 3 and Number at respective index is: 7
Index positioning: 4 and Number at respective index is: 9
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.