检查字符串是否包含嵌套列表的值 - python

时间:2016-04-30 16:25:22

标签: python nested-lists

首先,你知道为什么这段代码根本不起作用吗?当我给出它的输入时,当史蒂夫的工作出生时#39;什么也没有回报。其次,我几乎可以肯定,这可以用更有效的方式编写,这将花费更少的时间来执行程序。有任何想法吗?谢谢!

import sys

Bill_Gates = ["bill gates","1955", "Co-founder of Microsoft"]
Steve_Jobs = ["steve jobs","1955", "Co-Founder of Apple"]
Albert_Einstein = ["albert einstein","1879", "Phycisist"]

PEOPLE = [Bill_Gates, Steve_Jobs, Albert_Einstein]

userInput = input("say something")

#checking if userInput contains the peoples name
if userInput in [j for i in PEOPLE for j in i]:
    for i in range(len(PEOPLE)):
        if PEOPLE [i][0] in userInput:
            if "when was" in userInput:
                if "born" in userInput:
                    print(PEOPLE[i][0] + "was born in " + PEOPLE[i][1])

更新: Ahsanul Haque给了我正在寻找的答案。

3 个答案:

答案 0 :(得分:4)

你应该尝试通过分解每一步发生的事情来自己调试这些问题。在每个阶段打印变量或使用shell或调试器(如pdb)进行游戏都非常有用。在这种情况下:

>>> Bill_Gates = ["bill gates","1955", "Co-founder of Microsoft"]
>>> Steve_Jobs = ["steve jobs","1955", "Co-Founder of Apple"]
>>> Albert_Einstein = ["albert einstein","1879", "Phycisist"]
>>> 
>>> PEOPLE = [Bill_Gates, Steve_Jobs, Albert_Einstein]
>>> things = [j for i in PEOPLE for j in i]
>>> things
['bill gates', '1955', 'Co-founder of Microsoft', 'steve jobs', '1955', 'Co-Founder of Apple', 'albert einstein', '1879', 'Phycisist']
>>> 'steve jobs' in things
True
>>> 'when was steve jobs born' in things
False

所以if userInput in [j for i in PEOPLE for j in i]失败了,因为右边只是一个字符串列表而Python并不神奇。

无论如何,你的代码几乎都存在,因为它没有初步检查。所以这有效:

for person in PEOPLE:
    if person[0] in userInput and "when was" in userInput and "born" in userInput:
        print(person[0] + " was born in " + person[1])

请注意,直接for循环适用于这种情况;无需手动使用range和索引。使用and运算符也比嵌套的if语句更清晰。

除非PEOPLE有数千万个元素,否则效率非常高。如果你进入那个阶段,你可以研究搜索引擎索引技术。

答案 1 :(得分:2)

'when was steve jobs born'不在您制作的列表中,无论它是什么;由于外部if失败,因此内部没有任何内容被执行。

答案 2 :(得分:1)

制作Person课程怎么样?它简单易读,易于管理。

例如,我使用Person方法编写了get_role类。编写自己的get_name()get_year_of_birth方法。

class Person:
    def __init__(self, name, year_of_birth, role):
        self.name = name
        self.year_of_birth = year_of_birth
        self.role = role

    def get_role(self):
        return self.role

Bill_Gates = Person("bill gates","1955", "Co-founder of Microsoft")
Steve_Jobs = Person("steve jobs","1955", "Co-Founder of Apple")
Albert_Einstein = Person("albert einstein","1879", "Phycisist")


person_list= [Bill_Gates,Steve_Jobs,Albert_Einstein]


for person in person_list:
    print person.get_role()

输出:

Co-founder of Microsoft
Co-Founder of Apple
Phycisist