在Python 2D列表中搜索多个索引

时间:2015-12-07 00:06:40

标签: python python-3.x python-3.3

我已经以2D列表的形式创建了一个简单的数据库,您可以在其中添加记录,查找记录,删除记录并打印所有记录。

record_db = []
#this is where I have the menu function

数据库中的条目示例是:

['Sam', 'Smith', 25, 99.4]
#string, string, integer, float

现在我的问题是当我去做"找到记录"

我有这个:

def find_a_record():
    name = input("Enter the last name of record to find: ")
    if name in record_db:
        print('The following record was found in the database:')
        print(#this is where the record would go)
    else
        print('does not exist')

但是当您搜索数据库中的名称时,它表示“不存在”'总是

我知道这与索引有关,因为如果我这样做:

if name in record_db[0]

而不是

if name in record_db

它只会确认数据库中的第一条记录。

我的问题是如何编写代码以便检查整个数据库中的所有索引?

4 个答案:

答案 0 :(得分:3)

如果我了解您提供的内容,则record_db是一个列表列表。

检查if name in record_db时,它只会检查第一级。哪个总是返回false。由于列表record_db中没有字符串,因此只列出。

因此,您希望使用for循环遍历您的record_db,然后检查条目中是否name

record_db = [] # created as empty
# new entries are added for test case
# each entry is a list
record_db.append( ['Sam', 'Smith', 25, 99.4] )
record_db.append( ['Paul', 'Roberts', 35, 96.4] )
record_db.append( ['Bob', 'Sanders', 23, 89.4] )
record_db.append( ['Phil', 'Smith', 27, 95.4] )

def find_a_record():
    name = input("Enter the last name of record to find: ")
    results = []
    # for each entry in record_db
    for entry in record_db:
        # check if name is in that entry
        # will append all matching entry to results
        if name in entry:
            results.append(entry)
    # If results found
    if results:
        print('The following record(s) were found in the database:')
        print(results)
    else:
        print('does not exist')

如果您希望在新行上打印每条记录而不是仅打印列表,也可以使用以下内容替换print(results)

for record in results:
    print(record)

True和False案例的输入和输出示例

#Input
Enter the last name of record to find: Smith

#Output
The following record(s) were found in the database:
['Sam', 'Smith', 25, 99.4]
['Phil', 'Smith', 27, 95.4]

#Input
Enter the last name of record to find: Thing
does not exist

旁注

如果您想确定只检查姓氏,请将if name in entry替换为if name == entry[1]

答案 1 :(得分:0)

最简单 - 我认为 - 将根据条件过滤您的记录列表:

filter(lambda record: name in record[0], record_db)

这样做是过滤(...)您的列表或记录(record_db),并且对于该列表中的每个元素执行lambda(匿名函数)并仅返回项目哪个表达式是真的。

在这种情况下,它会测试记录的第一个元素是否包含变量name标识的字符串。

如果您想要搜索姓氏,请更改为name in record[1]

更有趣的是,您可以制作更复杂的过滤器:

filter(lambda record: name in record[1] and age<record[2], record_db)
按姓氏和年龄

query

答案 2 :(得分:0)

由于艺术家的名字和姓氏位于记录的单独索引中,您需要搜索每条记录并将输入的名称与两个值的串联进行比较:

for record in record_db:
    if name == '{0} {1}'.format(record[0], record[1]):
        <YOU FOUND IT>
        break

答案 3 :(得分:0)

哦,record_db是一个列表列表,但name是一个字符串。列表列表中没有字符串。因此,您可以遍历record_db并检查record_db内的每个列表。

相关问题