【发布时间】:2018-12-31 22:38:22
【问题描述】:
我有一个列表,在那个列表中,我有很多重复的值。这是列表的格式:
所以我有一些字段,按以下顺序:“User_ID”“Movie_ID”“Rating”“Time”
我想要做的是,从第 5 次出现的“User_ID”中删除,直到找到不同的“User_ID”。例如:
假设我有一个只有“User_ID”(从 1 到 196)的列表,如下所示:
1, 1, 1 ,1 ,1, 1, 2 ,2 , 2, 2, 2, 2, 2...
在这种情况下,我有 6 个数字 1 和 7 个数字 2。
所以,我将在第五次出现后从 1 中删除,直到找到第一个“2”。对于 2 也是一样:我将在其第五次出现后开始删除,直到找到一个新数字,即“3”,依此类推。
所以,我会得到一个新的列表,如下所示:1, 1, 1, 1, 1, 2, 2, 2, 2, 2 每个不同元素仅包含 5 个实例。
我知道我可以像这样访问所有“User_ID”字段:list[index]["User_ID"]
有这样的功能吗?或者如果没有,有人可以帮我创建一个吗?
感谢您的帮助!
我想做的是这样的:
a = 0
b = 1
start = 0
position = 0
while(something that I don't know):
while(list[a]['User_ID'] == list[b]['User_ID']): #iterate through the list, and I only advance to the next elements if the previous and next elements are the same
a+=1
b+=1
position+=1
if(list[a]['User_ID'] != list[b]['User_ID']): #when I finally find a different element
del new_list[start:start+position] #I delete from the start position, which is five untill the position before the different element.
a+=1
b+=1
start+=5
【问题讨论】:
-
将所有相关数据直接作为文本发布在这里。另外,你试过什么?您具体需要哪些帮助?
-
此列表是否按 user_id 排序,如果不是,您是否只想删除超过 5 个的相邻重复项或超过 5 个的任何重复项?
-
按user_id排序。我想删除超过 5 次的所有重复项
标签: python python-3.x list list-comprehension