首页 > 解决方案 > 通过for循环使用列表元素进行Python编号

问题描述

我有一个字典列表,还有一个注释元素,如何在打印这个列表时打印带有注释的数字,

  1. 示例评论
  2. 另一个示例评论

这是我在 python 中的代码

entries = [{'First Name': 'Sher', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '2989484'},
           {'First Name': 'Ali', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '398439'},
           {'First Name': 'Talha', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '3343434', 'comments': []}]

search = input("type your search: ")
        if search in [person['Last Name'] for person in entries]:
            for person in entries:
                if person["Last Name"] == search:
                    print("Here are the records found for your search")
                    for e in person:
                        if e == "comments":
                            for comment in person["comments"]:
                                print(comment)
                        else:
                            print(e, ":", person[e])
        else:
            print("There is no record found as you search Keyword")

标签: pythonlistloopsdictionaryfor-loop

解决方案


您可以使用enumerate

entries = [{'First Name': 'Sher', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '2989484'},
           {'First Name': 'Ali', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '398439'},
           {'First Name': 'Talha', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '3343434', 'comments': ['Comment 1','Comment 2']}]

search = input("type your search: ")
if search in [person['Last Name'] for person in entries]:
    for person in entries:
        if person["Last Name"] == search:
            print("Here are the records found for your search")
            for e in person:
                if e == "comments":
                    for index,comment in enumerate(person[e]):
                        print(f"{index+1}. {comment}")
                else:
                    print(e, ":", person[e])
else:
    print("There is no record found as you search Keyword")

输出:

type your search: >? Khan
Here are the records found for your search
First Name : Sher
Last Name : Khan
Age : 22
Telephone : 2989484
Here are the records found for your search
First Name : Ali
Last Name : Khan
Age : 22
Telephone : 398439
Here are the records found for your search
First Name : Talha
Last Name : Khan
Age : 22
Telephone : 3343434
1. Comment 1
2. Comment 2

推荐阅读