如何输入和打印列表中的特定值?

时间:2018-09-18 04:30:07

标签: python python-3.x

我需要能够输入多个姓氏和名字,还需要输入多个分数,这些分数与列表中的特定姓氏和名字相关/相关。我还需要能够搜索一个名字,然后打印出该人获得的分数的名字和姓氏。

4 个答案:

答案 0 :(得分:2)

建立字典,如:

data = {'record1':{'firstname':'abc', 'lastname':'xyz', 'score':20},
        'record2':{'firstname':'cde', 'lastname':'def', 'score':30},...}

使用以下方式访问:

print data['record1']['firstname']

您还可以用作:

print [ftype['firstname'] for f,ftype in data.iteritems() if f == 'record1' and 'firstname' in ftype]

输出将为 abc

答案 1 :(得分:0)

使用Python字典会很好。如果您希望将其添加到列表中,那么以下代码将对您有所帮助:

list1 = [["Akshay", "Gujar", 12], ["abc", "xyz", 45]]
find_name = "Akshay"
for i in range(len(list1)):
    if find_name in list1[i]:
        print("First Name:", list1[i][0])
        print("Last Name:", list1[i][1])
        print("Score:", list1[i][2])

名字:Akshay

姓氏:Gujar

得分:12

答案 2 :(得分:0)

这是您要完成的工作,它将创建您需要的词典数量,然后最后可以按名称搜索条目以检索信息

entries = int(input("How many entries? "))
lista = []
for i in range(entries):
    dicta = {}
    f_name = input("Enter First Name: ")
    dicta['First Name'] = f_name
    l_name = input("Enter Last Name: ")
    dicta['Last Name'] = l_name
    scores = int(input("How many scores? "))
    if scores == 0:
        dicta['Scores'] = []
    else:
        for i in range(scores):
            if 'Scores' not in dicta:
                score = int(input("Enter score: "))
                dicta['Scores'] = [score]
            else:
                score = int(input("Enter score: "))
                dicta['Scores'].append(score)
    lista.append(dicta)

while True:
    search = input("Enter a name: ")
    for i in lista:
        if i['First Name'] == search or i['Last Name'] == search:
            print(f"Name: {i['First Name']} {i['Last Name']}")
            print(f"Scores: {i['Scores']}")
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 noregex.py
How many entries? 1
Enter First Name: Vash
Enter Last Name: Stampede
How many scores? 2
Enter score: 9000
Enter score: 1
Enter a name: Vash
Name: Vash Stampede
Scores: [9000, 1]

答案 3 :(得分:0)

尝试如下所示的方法,迭代槽并将其格式化:

data = {'record1':{'firstname':'abc', 'lastname':'xyz', 'score':20},
        'record2':{'firstname':'cde', 'lastname':'def', 'score':30}}
for k,v in data.items():
   print(', '.join(' : '.join(map(str,i)) for i in v.items()))

输出:

firstname : abc, lastname : xyz, score : 20
firstname : cde, lastname : def, score : 30