如何检查列表列表中是否有重复的列表?

时间:2019-04-23 22:34:40

标签: python list set mutable

我有一个包含列表的列表结果。我只想在不存在的结果中添加一个列表。

所以

input = [1,2,3]
RESULT = [[5,6], [4,5,8]]

现在,RESULT.append(input)给出了

RESULT = [[5,6], [4,5,8], [1,2,3]]

现在,如果我尝试append [5,6],则不应该将其添加为已存在。

我在这里不能使用set,那有什么选择呢?

4 个答案:

答案 0 :(得分:3)

def add(data_, value):
    if value not in data_:
        data_.append(value)

data = [[5, 6], [4, 5, 8]]
print(data)  # [[5, 6], [4, 5, 8]]
add(data, [1, 2, 3])
print(data)  # {(5, 6), (4, 5, 8), (1, 2, 3)}
add(data, [5, 6])
print(data)  # {(5, 6), (4, 5, 8), (1, 2, 3)}

答案 1 :(得分:2)

您可以使用itertools.groupby()

no_dupes = list(ls for ls, _ in itertools.groupby(ls))

然后对其进行检查:

if ls == no_dupes:
     # Do x

答案 2 :(得分:1)

最简单的解决方案可能是使用if语句首先检查[5,6]中是否还没有RESULT,如果不是append,则继续检查,可能会向用户报告它是重复的但没有附加:

myinput = [1,2,3]
RESULT = [[5,6], [4,5,8]]

RESULT.append(myinput)

l = [5,6]

if l not in RESULT:
    RESULT.append(l)
else:
    # Do something with RESULT 
    pass # or
    # print('Duplicate not appended')
    print(f'RESULT: {RESULT}')
    raise(Exception(f'{l} is a duplicate and thus was not appended'))

输出:

RESULT: [[5, 6], [4, 5, 8], [1, 2, 3]]
Traceback (most recent call last):
  File "main.py", line 15, in <module>
    raise(Exception(f'{l} is a duplicate and thus was not appended'))
Exception: [5, 6] is a duplicate and thus was not appended

答案 3 :(得分:0)

    function updateForm(){
  // call your form and connect to the drop-down item
  var form = FormApp.openById("1jkvyqmRwK_U9Ddn96LRRAxC0xjnuufo3JuIj9kszNQ8");

  var namesList = form.getItemById("1425039677").asListItem();




// identify the sheet where the data resides needed to populate the drop-down
  var ss = SpreadsheetApp.getActive();
  var names = ss.getSheetByName("Student Names");

  // grab the values in the first column of the sheet - use 2 to skip header row 
  var namesValues = names.getRange(2, 1, names.getMaxRows() - 1).getValues();

  var studentNames = [];

  // convert the array ignoring empty cells
  for(var i = 0; i < namesValues.length; i++)    
    if(namesValues[i][0] != "")
      studentNames[i] = namesValues[i][0];

  // populate the drop-down with the array data
  namesList.setChoiceValues(studentNames);

假设在附加input = [1,2,3] RESULT = [[5,6], [4,5,8]]

之后
RESULT.append(input)

此特定代码的基本概念:

用于检查:

RESULT=[[5,6], [4,5,8], [1,2,3]]