Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have several dictionaries for each day of the week, Sunday ["a", "b", "c"], Monday ["d", "f", "g"], and so on, they are located in another script (xscript.py), and I would want to print them out depending on the day of the week I'm currently on, something like this:

import datetime
import xscript

def print_daily_list():
    day_of_week = datetime.datetime.today().weekday()
    print(xscript.day_of_week)

I wouldn't want to create a bunch of if statements to replace day_of_week with "Sunday" or "Monday" depending on the day.

question from:https://stackoverflow.com/questions/65713742/replace-list-name-with-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
103 views
Welcome To Ask or Share your Answers For Others

1 Answer

This solution uses getattr to get the attribute of an object in this instance the module xscript. If the script module has a variable named Thursday and today is Thursday this script will get and print that variable.

day_of_week = datetime.datetime.today().strftime('%A')
print(getattr(xscript, day_of_week))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...