如果以下列表包含相同的元素,请删除所有以前的列表

时间:2016-04-18 16:12:19

标签: python list

对于示例,我有一些列表:

[date1, time1, nickname1, point1 = 56.341708,43.948463]
[date2, time2, nickname2, point2 = 56.321795,43.9996]
[date3, time3, nickname3, point1 = 56.341708,43.948463]
[date4, time4, nickname4, point1 = 56.341708,43.948463]
[date5, time5, nickname5, point3 = 56.236278,43.960233]
[date6, time6, nickname7, point3 = 56.236278,43.960233]

如果以下列表具有相同的点,我需要删除所有以前的列表。 正确的输出应该是:

[date2, time2, nickname2, point2 = 56.321795,43.9996]
[date4, time4, nickname4, point1 = 56.341708,43.948463]
[date6, time6, nickname7, point3 = 56.236278,43.960233]

我的代码删除了一些列表,但它没有完全完成任务:

checked3 - 列表清单 checked4 - 积分列表

代码:

r = -1
v = -2
k = -len(checked3)
try:
    while v > k:
        if str(checked4[r]) in checked3[v]:
            checked3.pop(v)
            print ('now', checked3)
            v = v - 1
        else:
            print ('else', checked3)
            r = r - 1
except:
    pass

你能帮帮我吗,我怎样才能得到正确的输出?

2 个答案:

答案 0 :(得分:1)

这应该有效

distinctList = []
distinctDict = {}

for l in checked3:
    point = l[-1] #last element of inside list
    distinctDict[point] = l

for l in distinctDict:
    distinctList.append(distinctDict[l])

答案 1 :(得分:0)

这是一种方法:

  1. 创建点词典。
  2. 从后面走列表(因为您希望保留最后一个值)
  3. 找到项目首次出现时举报
  4. 找到重复点时删除
  5. 为了简化说明,我模拟了一个列表,这些列表包含无关紧要字段和点元组的字符串。

    listOfLists = [
    ['date1', 'time1', 'nickname1',  (56.341708,43.948463)],
    ['date2', 'time2', 'nickname2', (56.321795,43.9996)],
    ['date3', 'time3', 'nickname3', (56.341708,43.948463)],
    ['date4', 'time4', 'nickname4', (56.341708,43.948463)],
    ['date5', 'time5', 'nickname5', (56.236278,43.960233)],
    ['date6', 'time6', 'nickname7', (56.236278,43.960233)]
    ]
    

    使用字典理解,为每个点创建一条记录

    pointsDict = {item[3]:'Duplicates in list' for item in listOfLists}
    

    从后面走向逆转列表。我们通过更改与该点相对应的值来标记删除,以将其设置为“可以删除'”。当我们遇到'可以删除'作为与迭代中的项对应的值,我们将其从原始列表中删除。

    for item in listOfLists[::-1]:
        point = item[3]
        if pointsDict[point] == 'Duplicates in list':
            pointsDict[point] = 'Can delete'
        elif pointsDict[point] == 'Can delete':
            listOfLists.pop(listOfLists.index(item))
    

    此时listOfLists包含您想要的内容。