【问题标题】:Python Numbering with list element by for Loop通过for循环使用列表元素进行Python编号
【发布时间】:2020-11-08 09:47:36
【问题描述】:

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

  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")

【问题讨论】:

    标签: python list loops dictionary for-loop


    【解决方案1】:

    你可以使用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
    

    【讨论】:

    • 如果我从用户那里得到输入怎么办,例如用户给出输入 2. 我想删除 commnet no.2 。 ?
    • 您必须为此使用单独的输入语句和单独的循环
    • 你可以自己试试。如果你做不到,那么你可以在这里问,或者作为一个单独的问题问,这样我就可以帮助你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    相关资源
    最近更新 更多