Python 如何从列表中输入和打印特定值?
我需要能够在列表中输入多个姓氏和名字,以及与特定姓氏和名字相关的多个分数。我还需要能够搜索一个名字,然后打印出名字和姓氏以及该人得到的分数。构建字典,如:Python 如何从列表中输入和打印特定值?,python,python-3.x,Python,Python 3.x,我需要能够在列表中输入多个姓氏和名字,以及与特定姓氏和名字相关的多个分数。我还需要能够搜索一个名字,然后打印出名字和姓氏以及该人得到的分数。构建字典,如: data = {'record1':{'firstname':'abc', 'lastname':'xyz', 'score':20}, 'record2':{'firstname':'cde', 'lastname':'def', 'score':30},...} 访问使用: print data['record1']['
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最好使用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
姓:古贾
分数:12这是您试图完成的任务。它将创建您需要的词典数量,然后在最后您可以按名称搜索条目以检索信息
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']}")
尝试以下方法,迭代槽并格式化它:
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
到目前为止你做了什么?不幸的是,“我需要”不是一个问题,而是一个要求。请显示示例数据和预期输出以及您尝试的代码。我们需要知道您迄今为止尝试了什么,它是如何不起作用的,以及您在哪里搜索以尝试自己解决此问题。
firstname : abc, lastname : xyz, score : 20
firstname : cde, lastname : def, score : 30