搜索嵌套列表中的值

时间:2018-05-04 19:31:55

标签: python python-3.x list nested

我有一个数据库文件,csv文件。我想在此列表中搜索名称。要知道它是否存在。如果没有显示要添加的选项。名称旁边的数字是客户编号。我如何搜索此列表中的值?

lines=[]
user_name=input("PLEASE ENTER YOUR FIRST AND LAST NAME: ")
with open("data_base.csv", "r") as in_file:
    for line in in_file:
        row = line.split(",")
        for i in range(1, len(row)):
            row[i] =eval(row[i])
            lines.append(row)

如果我打印列表,结果就是下一个:

[['Mariana Ortigoza', 1], ['James Butt', 2], ['Josephine Darakjy', 3], ['Art Venere', 4], ['Lenna Paprocki', 5], ['Donette Foller', 6], ['Simona Morasca', 7], ['Mitsue Tollner', 8], ['Leota Dilliard', 9], ['Sage Wieser', 10]]

1 个答案:

答案 0 :(得分:0)

一种方法是使用operator.itemgetter来提取每个子列表的第一个元素。

然后测试输入名称是否在set个名称中;如果没有,则附加到lines

from operator import itemgetter

lines = [['Mariana Ortigoza', 1], ['James Butt', 2], ['Josephine Darakjy', 3],
         ['Art Venere', 4], ['Lenna Paprocki', 5], ['Donette Foller', 6],
         ['Simona Morasca', 7], ['Mitsue Tollner', 8], ['Leota Dilliard', 9],
         ['Sage Wieser', 10]]

user_name = input("PLEASE ENTER YOUR FIRST AND LAST NAME: ")

if user_name not in set(map(itemgetter(0), lines)):
    lines.append([user_name, len(lines)+1])