【问题标题】:remove duplicate nested list based on item in list根据列表中的项目删除重复的嵌套列表
【发布时间】:2020-12-21 12:24:42
【问题描述】:

我有一个 CSV 文件,每次更新数据时,我的意思是行 .. 两件事我现在想做但做不到。 如何根据此删除重复列表

输入:

[name , age , school]
[jack, 76, oxford ],
[march , 32, cfr],
[bee, 43, oi],
[jack ,15, iuy]

输出:

[name , age , school],
[jack, 76, oxford ],
[march , 32, cfr],
[bee, 43, oi]

注意:set(list) 不会对我的情况做任何事情

如您所见,第二个插孔没有添加到列表中 _ 这就是我想要的

和(第二件事)当我收到新行时现在怎么办它检查名称是否存在,如果不存在则不会添加新行,否则它将添加

【问题讨论】:

  • 创建一个空集,并为每一行检查名称是否在集合中。如果名称不在集合中,则将名称添加到集合中

标签: python csv duplicates nested-lists


【解决方案1】:
all_list = []

#beforeUpdating
for j in all_list:
    if j == csvlist[0] #considering all names are on index - 1:
        #cancel upload
        break
    
#AfterUpdating
for i in csvlist:
    all_list.append(i)

我可以为您提供此信息,因为您尚未发布您的代码。希望这能给你一个想法。

【讨论】:

    【解决方案2】:
    1. 利用set 跟踪添加的名称
    2. 遍历列表项:
      2.1.如果未添加当前名称
      2.2.添加当前项目
      2.3.更新集
    original_list = [['name', 'age', 'school'],
    ['jack', '76', 'oxford '],
    ['march', '32', 'cfr'],
    ['bee', '43', 'oi'],
    ['jack', '15', 'iuy']]
    
    added_names = set()
    filtered_list = []
    for item in original_list:
        current_name = item[0]
        if current_name not in added_names:
            filtered_list.append(item)
            added_names.add(current_name)
    
    print(filtered_list)
    

    输出:

    ['name', 'age', 'school'], 
    ['jack', '76', 'oxford '], 
    ['march', '32', 'cfr'], 
    ['bee', '43', 'oi']
    

    要更新,只需检查名称是否已存在于集合中。

    【讨论】:

    • 非常感谢..我点击了投票,但这就是结果..感谢您的反馈!声望低于 15 人的投票将被记录,但不会更改公开显示的帖子得分。
    【解决方案3】:

    第一个 Csv 文件包含此值:

    duplicated = [  ['name' , 'age' , 'school'],
                    ['jack', 76, 'oxford' ],
                    ['march' , 32, 'cfr'],
                    ['bee', 43, 'oi'],
                    ['jack' ,15, 'iuy'],
                    ['name' , 'age' , 'school']
                 ]
    

    当你执行这段代码时

     #!/usr/bin/python3.8.2    
    import csv
    
    duplicated = []
    names = []
    clear = []
    
    with open('python.csv', 'r') as file:
        reader = csv.reader(file)
        for row in reader:
            duplicated.append(row)
    
    for i in duplicated:
        if i[0] not in names :
            names.append(i[0])
    
    for i in duplicated:
        if i[0] in names and i not in clear :
            clear.append(i)
            names.remove(i[0])
    
    for i in clear:
        print(i)
    

    输出应该是:

    ['nom', 'age', 'scholl']
    ['jack', '76', 'oxford']
    ['march', '32', 'cfr']
    ['bee', '43', 'oi']
    ['jack', '15', 'iuy']``
    

    这是你想要的:)

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 1970-01-01
      • 2020-02-05
      • 2018-02-18
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多