在列表中查找和打印项目?

时间:2016-03-03 22:47:09

标签: python list python-3.x

我希望从列表中绘制内容并将其打印出来,就像数据库一样。如何打印用户要求的内容?

name = [John, Sam]
ages = [23, 7]
answer = input("Search by (n)ame or (a)ge")
if answer == "n":
    askName= input("what name?")
    # ?????
elif answer == "a":
    askAge = input("what age")
else start()

2 个答案:

答案 0 :(得分:3)

name = ['John', 'Sam']
ages = [23, 7]
answer = input("Search by (n)ame or (a)ge")
if answer == "n":
    askName= input("what name?")
    if askName in name:
        print(ages[name.index(askName)])
elif answer == "a":
    askAge = input("what age")
    if askAge in ages:
        print(name[ages.index(askAge)])

使用if askName in name,您可以检查askName列表中是否有name。如果是,您可以使用index()获取索引并使用它访问ages列表中的值。获得一个年龄的名称也是一样的。

答案 1 :(得分:0)

您可以使用字典:

#!/usr/bin/python
userlist = [
    {'name':'John', 'age':23},
    {'name':'Sam', 'age':7},
    {'name':'Anna', 'age':7},
    {'name':'John', 'age':10},
]

answer = input("Search by (n)ame or (a)ge")
if answer == "n":
    askName= input("what name?")
    for i in userlist:
        if i['name'] == askName:
            print('name: '+askName+', age: '+str(i['age']))
elif answer == "a":
    askAge = input("what age")
    for i in userlist:
        if i['age'] == int(askAge):
            print('name: '+str(i['name'])+', age: '+askAge)

学生可以有相同的名字和年龄,所以输出将是这样的:

Search by (n)ame or (a)gen
what name?Sam
name: Sam, age: 7

Search by (n)ame or (a)gea
what age7
name: Sam, age: 7
name: Anna, age: 7

为避免这种情况,您可以按ID选择学生:

#!/usr/bin/python
userlist = [
    {'name':'John', 'age':23},
    {'name':'Sam', 'age':7},
    {'name':'Anna', 'age':7},
    {'name':'John', 'age':10},
]

answer = input("Search by (n)ame or (a)ge or (i)d\n")
if answer == "n":
    askName= input("what name?\n")
    for i in userlist:
        if i['name'] == askName:
            print('name: '+askName+', age: '+str(i['age']))
elif answer == "a":
    askAge = input("what age?\n")
    for i in userlist:
        if i['age'] == int(askAge):
            print('name: '+str(i['name'])+', age: '+askAge)
elif answer == "i":
    askId = input("what id?\n")
    print('id: ' + askId + ',name: '+str(userlist[int(askId)]['name'])+', age: '+str(userlist[int(askId)]['age']))

输出:

Search by (n)ame or (a)ge or (i)d
i
what id?
1
id: 1,name: Sam, age: 7