提问人:UntilComputersTakeOver 提问时间:1/29/2023 最后编辑:UntilComputersTakeOver 更新时间:1/29/2023 访问量:94
如何在 python 列表中查找元素第 n 次出现的位置
How to find the location of the nth occurrence of an element in a python list
问:
我需要创建一个接受两个参数的函数:一个列表 lst 和一个数字 num。如果元素在 lst 中出现超过 num 次,请删除多余的出现次数并返回结果。
到目前为止,我有:
def delete_occurrences(lst, num):
for x in lst:
if lst.count(x) > num:
lst.pop(lst.index(x, lst.index(x)+1))
return lst
但是,对于诸如 ([1, 1, 3, 3, 7, 2, 2, 2, 2], 3) 的情况 它不会删除正确的重复项。
答:
1赞
Nehal Birla
1/29/2023
#1
def delete_occurrences(lst, num):
i = 0
while i < len(lst) :
if lst.count(lst[i]) > num:
lst.pop(i)
i-=1
i+=1
return lst
1赞
Swifty
1/29/2023
#2
下面是一个解决方案,它保留了你的一般逻辑,以相反的顺序解析列表,以免弄乱迭代:
def delete_occurrences(lst, num):
for i in range(len(lst)-1,-1,-1):
if lst.count(lst[i]) > num:
lst.pop(i)
return lst
3赞
Timeless
1/29/2023
#3
IIUC,使用 list.count
和 listcomp 来切分额外发生的事件:
L = [1, 1, 3, 3, 7, 2, 2, 2, 2]
def delete_occurrences(lst, num):
return [x for i, x in enumerate(lst) if lst[:i+1].count(x) <= num]
输出:
delete_occurrences(L, 3)
#[1, 1, 3, 3, 7, 2, 2, 2]
评论
1赞
DarrylG
1/29/2023
也许因为只有在“lst 超过 num 次”时才删除<= num
0赞
DarrylG
1/29/2023
此外,我们希望在计数中包含当前索引,因此应该(即发布的解决方案不正确if lst[:i+1].count(x) <= num
delete_occurrences(L, 1)
)
0赞
Timeless
1/29/2023
很公平,答案已更新。谢谢DarryIG;)
1赞
DarrylG
1/29/2023
实际上,如果你忽略我的两个建议,那么你原来的答案也是正确的。
0赞
RifloSnake
1/29/2023
#4
这以您喜欢的方式工作:
def delete_occurrences(lst, num):
element_work_done = []
for element in lst:
if lst.count(element) > num and element not in element_work_done:
elm_indices = [i for i, x in enumerate(lst) if x == element]
abundant_occurrences = elm_indices[-(lst.count(element)-num):]
index = 0
for occurrence in abundant_occurrences:
lst.pop(occurrence-index)
index += 1
element_work_done.append(element)
return lst
对于更大的列表和数据样本,此函数的执行速度比其他方法快 10 倍。
评论