什么是好的词典搜索功能

2024-09-27 21:24:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在使用这个,但它似乎不适用于多个条目每次我做搜索后添加第二个条目,如果我试图搜索第一个条目,它会出现第二个。什么是修复

        for i in range(len(gclients)):
            record = gclients[i]
            if record["Name"].lower() == search1:
                if record["Surname"].lower() == search2:
                    recordfoundc = True


            for k,v in record.iteritems():
                resname = record["Name"]
                resSurname = record["Surname"]
                resnum = record["Phone Number"]
                resjob = record["Job"]
                resaddress = record["Address"]
                resemID = record["Employee ID"]

        if recordfoundc:
            print"You have just found",resname,resSurname,resnum,resjob, resaddress, resemID
            recordfoundc =  False

        else:
            print "Client not found"

Tags: nameinforif条目surnamerecordlower
2条回答

与代码相关:

if loop(在recordfoundc = True之后)内移动for k,v in record.iteritems():for循环代码,因为当找到Employee时,只有从records获取Employee详细信息。你知道吗

不需要for k,v in record.iteritems():语句因为我们直接从记录中访问键和值,并且在代码中不使用变量kv。你知道吗

同时使用break语句。你知道吗

代码看起来像-:

recordfoundc = False
for i in range(len(gclients)):
    record = gclients[i]
    if record["Name"].lower() == search1 and record["Surname"].lower() == search2:
        recordfoundc = True
        #- Get Details of Employee.
        resname = record["Name"]
        resSurname = record["Surname"]
        resnum = record["Phone Number"]
        resjob = record["Job"]
        resaddress = record["Address"]
        resemID = record["Employee ID"]

        break

if recordfoundc:
    print"You have just found",resname,resSurname,resnum,resjob, resaddress, resemID
else:
    print "Client not found"

Python允许用andor关键字在if循环中编写多个条件。你知道吗

演示:

>>> a = 1
>>> b = 2
>>> c = 3
>>> if a==1 and b==2 and c==3:
...   print "In if loop"
... 
In if loop
>>> 

中断语句

当满足任何条件时,使用break语句退出any while。你知道吗

在我们的例子中,当员工的名字和姓氏在记录中匹配时,则不需要签入其他记录项。你知道吗

演示:3i的值时中断for loop。你知道吗

>>> for i in range(5):
...    print i
...    if i==3:
...       print "Break for loop."
...       break
... 
0
1
2
3
Break for loop.

如何从字典中获得价值。你知道吗

演示:

>>> record = {"name": "test", "surname":"test2", "phone":"1234567890", "Job":"Developing"}
>>> record["name"]
'test'
>>> record["surname"]
'test2'
>>> record["Job"]
'Developing'
>>> 

打印输出发生在for循环完成之后,因此结果变量只是您最后编写的变量(并且这些变量只需要在记录匹配的情况下写入,如注释中所指出的)。您需要在for中打印,或者将结果添加到列表中以便以后打印。和/或如建议的那样,如果您只想要第一个匹配,则从循环中断。你知道吗

相关问题 更多 >

    热门问题