python中两个列表的比较

时间:2016-01-25 17:35:16

标签: python list postgresql

我有一个列表,其中包含有关班级编号和关键字的信息。我称之为'class-list':

    [(0, ['word1', 'word2', 'word3', 'word4']), (1, ['word5', 'word6', 'word7', 'word8']), (2, ['word1', 'word9', 'word3', 'word7'])

我有一个postgres数据库,每个条目都有一个单词列表,比方说'db-list'。

    ['word1', 'word2', 'word10', 'word7', 'word3']

这个想法是根据'class-list'将类分配给数据库中的数据。如果'db-list'包含word1和word2,那么类'0'将被分配给该描述。 我不知道如何编写条件“如果'db-list'的两个元素(k)=='class-list'的两个元素”。任何帮助都非常感谢!

    cur.execute("SELECT * From table")
    dbrows = cur.fetchall()
    for k in dbrows:
        if two elements of the 'db-list' (of k) == two elements of the 'class-list':
            sql = "INSERT INTO table VALUES (class);"""
            cur.execute(sql)

1 个答案:

答案 0 :(得分:3)

您可以从交集子集中的关键字列表和计数元素创建集合。例如:

dblist = [(0, ['word1', 'word2', 'word3', 'word4']), (1, ['word5', 'word6', 'word7', 'word8']), (2, ['word1', 'word9', 'word3', 'word7'])]
dbrow = ['word1', 'word2', 'word10', 'word7', 'word3']

for class_idx, kwords in dblist:
    if len(set(dbrow) & set(kwords)) == 2:
        print kwords  # or do whatever you need