简体   繁体   English

For 循环枚举 - 索引位置

[英]For loop with enumerate - index position

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 ? list_input[0:num1]每个交互的位置是什么,考虑到我们已经用num1, num2开始了for循环?

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. Enumerate 迭代一个可迭代对象(在这个原因中为list_input ),并且每次迭代将第一个值(在本例中为num1 )设置为当前索引,将第二个值(在本例中为num2 )设置为此索引处的可迭代值.

For example, on first iteration, num1 == 0 as the iteration begins at the zeroeth element, and num2 == 1 as list_input[0] == 1 .例如,在第一次迭代中, num1 == 0作为迭代从第零个元素开始,而num2 == 1作为list_input[0] == 1 list_input[0:num1] == [] so nothing is in it and therefore the value is appended to the outputs. list_input[0:num1] == []所以里面什么都没有,因此该值被附加到输出。

On second iteration, the index has incremented by one and so num1 == 1 .在第二次迭代中,索引增加了 1,因此num1 == 1 list_input[0:num1] == [1] now, and as num2 is in [1] , the value is not appended to the output list. list_input[0:num1] == [1]现在,并且由于num2[1] ,该值不会附加到输出列表中。

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:但是,如果我理解正确,如果您想删除重复项并需要非重复项的每个元素(编号)的定位或索引,您可以使用 enumerate() 并可能执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM