简体   繁体   English

如何返回列表中元素的轮次?

[英]How to return the turn of an element in a list?

I want to know if an element is in the list multiple times and if so what is the order of the 2nd one.我想知道一个元素是否多次出现在列表中,如果是,第二个的顺序是什么。 The 2nd one is important, not the 3rd or the 4th one.第二个很重要,而不是第三个或第四个。

list = [1, 3, 4, 2, 0, 1, 6, 7, 0]

My expected output is:我预期的 output 是:

"1" is in list 2 times and the order of the 2nd "1" is six . “1”在列表中2 次,第二个“1”的顺序是6

Doing it with one pass over the list, while saving the indexes of the target number and checking their amount in the end:一次遍历列表,同时保存目标编号的索引并检查它们的数量:

l = [1, 3, 4, 2, 0, 1, 6, 7, 0]
target = 1

idxs = []
for i, num in enumerate(l):
    if num == target:
        idxs.append(i)

if len(idxs) > 1:
    print(f'"{target}" is in the list {len(idxs)} times and the order of the 2nd "{target}" is {idxs[1]+1}')
else:
    print(f'{target} is in the list 0 or 1 times')

The indexes can also be obtained with a neat list-comprehension:索引也可以通过简洁的列表理解获得:

idxs = [i for i, num in enumerate(l) if num == target]

Pretty rough code, just to convey the logic you can apply to get it done:相当粗略的代码,只是为了传达您可以应用的逻辑来完成它:

list = [1, 3, 4, 2, 0, 1, 6, 1, 7, 0]

flagged = []
for index, elem in enumerate(list):
    elem_count = list[index:].count(elem)
    if elem_count > 1 and elem not in flagged:
        flagged.append(elem)
        temp_index = list[index + 1:].index(elem)
        actual_index = index + temp_index + 1
        print(str(elem) + ' is in the list ' + str(elem_count) + ' times and the order of 2nd is ' + str(actual_index))

# OP
# 1 is in the list 3 times and the order of 2nd is 5
# 0 is in the list 2 times and the order of 2nd is 9

Are you sure it's 6 and not 5?你确定是6而不是5? Indexing starts from 0. In any case, you can use index for finding it:索引从 0 开始。在任何情况下,您都可以使用index来查找它:

first_idx = list.index(element)
print(list.index(element, first_idx + 1))

Like that you will find the first occurrence of the element and than return the index of the second one.像这样你会发现元素的第一次出现,然后返回第二个的索引。 If you want it 6 and not 5 - increment it by 1.如果你想要它 6 而不是 5 - 将它增加 1。

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

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