引用列表索引以枚举值 [英] Reference list index to enumerate value
问题描述
我有一个程序可以检查Outlook收件箱中是否有字典中特定发件人的附件. Python-Outlook仅在特定范围内搜索电子邮件
I have a program which checks an outlook inbox for attachments from specific senders in a dictionary. Python - Outlook search emails within specific range only
该程序运行良好,现在我正在尝试通过使用户能够从词典中选择特定发件人的功能来对其进行扩展,以便仅搜索其电子邮件.该代码在上一个程序中.
That program works fine, and now I'm trying to expand on it by giving the user the ability to choose a specific sender from the dictionary, so as to only search their emails. This code is within the previous program.
我的字典是senderDict = {sender@address.com : Sender Name}
要将其变成值菜单,以便从我使用的枚举中进行选择:
To turn it into a menu of values to choose from I've used enumerate:
listSender = list(senderDict.values())
for count, item in enumerate(listSender,1):
print(count, item)
print("There are", len(listSender), "items.")
while True:
senderNum = int(input("Choose a sender (zero for any): "))
try:
if senderNum <= len(listSender) and senderNum >= 0:
#senderNum = int(input("Choose a sender (zero for any): "))
print("you chose", listSender[senderNum])
break
elif senderNum == 0:
print("Searching for any sender")
break
elif senderNum < 0:
print("Cannot choose a negative number.")
continue
except ValueError: #Not int
print("You did not enter a valid number (ValueError)")
input()
except IndexError: #outside range
print("You did not enter a valid number (IndexError)")
input()
问题在于选择零将选择零索引,而不是搜索任何".如何使列表索引与枚举值匹配?
The issue is that choosing zero will choose the zero index, instead of 'search any'. How do I make the list index match the enumerate values?
此外,输入非数字或空白的输入会使程序崩溃,因此我不确定该覆盖什么异常,我认为它属于ValueError.
Also, entering a non-number or blank input crashes the program, so I'm not certain what exception covers that, I thought it fell under ValueError.
我不确定我是否甚至需要将字典转换成列表,但是我已经读到枚举必须工作,所以我就去了.
I'm not really sure if I even need to turn the dictionary into a list, but I had read that it was necessary for enumerate to work so I just went with it.
推荐答案
感谢所有有用的回复!
Thanks for all the helpful responses!
我决定不尝试更改输入的值,而是决定在将字典转换为列表之后为"Search Any"插入一个列表选项,然后让枚举从零开始.这样,我不必进行任何加法或减法,索引值仍与输入匹配.
Instead of trying to change the value of the input, I decided to insert a list option for 'Search Any' after converting the dictionary to a list, then let enumerate start from zero. This way I don't have to do any addition or subtraction and the index values still match the input.
listSender = list(senderDict.values())
listSender.insert(0, "Search Any")
for count, item in enumerate(listSender):
print(count, item)
这篇关于引用列表索引以枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!