如果尚未存在,则将项目添加到列表

时间:2015-08-07 12:48:43

标签: python list compare

我是Python新手,遇到了以下问题:

<script type="text/javascript" language="javascript" class="init">

$(document).ready(function() {
    $('.mytable').dataTable( {
        "scrollCollapse": true,
        "paging":         false
    } );
} );
</script>

输出应为:

a = [[0,abc,1],[0,def,1]]

b = [abc,jkl]

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:4)

可以使用以下代码完成:

In [3]: a = [[0,'abc',1],[0,'def',1]]
In [4]: b = ['abc','jkl']
In [5]: c = a[:]
In [6]: c.extend([[0,e,1] for e in b if e not in [x for _,x,_ in a]])
In [7]: c
Out[8]: [[0, 'abc', 1], [0, 'def', 1], [0, 'jkl', 1]]

希望这有帮助!

答案 1 :(得分:3)

这个怎么样?

>>> a = [[0,'abc',1],[0,'def',1]]
>>> b = ['abc','jkl']
>>> c = a[:]
>>> for i in b:
...     if [0,i,1] not in a:
...             c.append([0,i,1])
... 
>>> c
[[0, 'abc', 1], [0, 'def', 1], [0, 'jkl', 1]]

答案 2 :(得分:1)

使用不在中检查它是否包含

a = [[0,abc,1],[0,def,1]]

b = [abc,jkl]

c = []

for i in a:
    if i not in c:
       c.append(i)
for j in b:
    if j not in c:
       c.append(j)