python - 通过for循环使用列表元素进行Python编号
问题描述
我有一个字典列表,还有一个注释元素,如何在打印这个列表时打印带有注释的数字,
- 示例评论
- 另一个示例评论
这是我在 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")
解决方案
您可以使用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
推荐阅读
- haskell - 在haskell中搜索序列是否比向量快?
- java - 重载和 Java 类型概念
- azure - Azure Cosmos DB:Application Insights 中的 HTTP 400
- python - 按字母顺序对 csv 文件进行排序
- hyperledger-fabric - 在 fabcar.js 中添加数据
- mysql - 怎么了,我把所有的名字都记了两次?
- python - JSON相机点结构TypeError:预期的字符串或缓冲区
- qt - 带有 QtCreator 的 GDB 无法读取变量
- list - 从熊猫数据框创建列表
- regex - 带有换行符的匹配字符串的正则表达式