【问题标题】:Is there a way to check if elements in sub list are equall in any of the other sublists有没有办法检查子列表中的元素在任何其他子列表中是否相等
【发布时间】:2022-11-04 23:41:54
【问题描述】:

因此,我有一个包含 1000 个子列表的列表,其中子列表具有这种格式的日期“2022-01-01”和另一个列表的索引。所以列表看起来像这样 [["2022-01-01", 3], ["2010-01-01", 1], ["2022-01-01", 12]] 有 1000 个元素。

我想要得到的是一个带有子列表的新列表,它的日期索引是相等的。

所以输出应该是这样的 [[3, 12,]]。

我试过了

count = 0
for i in range(len(dateList)):
    if i != x:
        if dateList[i][0] == dateList[x][0]:
            print(dateList[i][0], dateList[x][0])
    count += 1

或者

for i in range(len(dateList)):
    for x in range(len(dateList)):
       if 1!= x:  
         if dateList[i][0] == dateList[x][0]:
            print(dateList[i][0], dateList[x][0])

我理解为什么两者都是错误的,我用它们来试图让我的想法得到正确的答案。但是我似乎找不到任何解决方案。

【问题讨论】:

    标签: python list


    【解决方案1】:

    您可以使用defaultdict 创建一个以日期为键的数据结构,其值是这些日期出现的索引。一旦你创建了这样一个东西,你可以迭代它的值,选择那些有多个条目的:

    from collections import defaultdict
    
    date_list = [["2022-01-01", 3], ["2010-01-01", 1], ["2022-01-01", 12]]
    
    d = defaultdict(list)
    
    for i,date_pair in enumerate(date_list):
        date = date_pair[0]
        d[date].append(i)
    
    duplicates = [v for v in d.values() if len(v) > 1]
    
    print(duplicates) #[[0,2]]
    

    【讨论】:

      猜你喜欢
      • 2014-07-10
      • 1970-01-01
      • 2013-09-19
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      • 2020-08-18
      相关资源
      最近更新 更多