gpt4 book ai didi

python - 用相应的工作日数字替换列表中的工作日字符串 ("MON"、 "TUE"等)

转载 作者:行者123 更新时间:2023-12-02 16:02:49 25 4
gpt4 key购买 nike

我让用户选择工作日的字符串,然后将其存储在列表中。我的目标是用它对应的 weekday number 替换任何用户选择的字符串.我的代码有效,但它似乎不必要地庞大。有没有更优雅的方式?

selected_weekdays = ["MON", "WED", "THU", "SAT"]

for i in range(len (selected_weekdays)):
if selected_weekdays[i] == "MON":
selected_weekdays[i] = 0
elif selected_weekdays[i] == "TUE":
selected_weekdays[i] = 1
elif selected_weekdays[i] == "WED":
selected_weekdays[i] = 2
elif selected_weekdays[i] == "THU":
selected_weekdays[i] = 3
elif selected_weekdays[i] == "FRI":
selected_weekdays[i] = 4
elif selected_weekdays[i] == "SAT":
selected_weekdays[i] = 5
elif selected_weekdays[i] == "SUN":
selected_weekdays[i] = 6
else:
pass

print(selected_weekdays)

正确的输出:

[0, 2, 3, 5]

最佳答案

您可以通过生成字典映射来避免一些额外的工作

最好避免修改您也出于各种原因迭代的结构
参见 Modifying list while iterating

字典 .get() 方法将选择一个默认选项(在您的原始情况下是工作日,尽管您可能想更改它以使其成为其中之一

  • 未列出的工作日(这是您的代码当前所做的,所以我保持结果不变)
  • 异常(KeyError 来自直接索引 [] .. 你可能希望它突出显示错误)
  • None(基本上丢弃错误的值,并且很容易在下一步中过滤)
# dictionary expression
weekday_mapping = {day: index for index, day in enumerate((
"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"))}

selected_weekdays = ["MON", "WED", "THU", "SAT"]
results = []
for weekday in selected_weekdays:
results.append(weekday_mapping.get(weekday, weekday))
>>> results
[0, 2, 3, 5]
>>> selected_weekdays = ["MON", "WED", "THU", "FakeDay", "SAT"]
...
>>> results
[0, 2, 3, 'FakeDay', 5]

关于python - 用相应的工作日数字替换列表中的工作日字符串 ("MON"、 "TUE"等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70202022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com