分享
三行代码  ›  专栏  ›  技术社区  ›  Bolmstead

为什么我用Python3在字典中得到这个无效语法?

  •  0
  • Bolmstead  · 技术社区  · 1 周前

    enter image description here

    def weekday_name(day_of_week):
        """Return name of weekday.
        
            >>> weekday_name(1)
            'Sunday'
            
            >>> weekday_name(7)
            'Saturday'
            
        For days not between 1 and 7, return None
        
            >>> weekday_name(9)
            >>> weekday_name(0)
        """
        weekdays = {
            "1": "Sunday"
            "2": "Monday"
            "3": "Tuesday"
            "4": "Wedensday"
            "5": "Thursday"
            "6": "Friday"
            "7": "Saturday"
        }
        return weekdays['day_of_week']
    
    1 回复  |  直到 1 周前
        1
  •  1
  •   kojiro    1 周前
    weekdays = {
            "1": "Sunday"
            "2": "Monday"
            "3": "Tuesday"
            "4": "Wedensday"
            "5": "Thursday"
            "6": "Friday"
            "7": "Saturday"
        }
    

    是无效语法。条目之间需要逗号,如

    weekdays = {
            "1": "Sunday",
            "2": "Monday",
            "3": "Tuesday",
            "4": "Wedensday",  # Wednesday?
            "5": "Thursday",
            "6": "Friday",
            "7": "Saturday",
        }
    

    顺便说一句,你也基本上把列表定义为字典。好吧,数字是字符串,但为什么呢?考虑一个列表:

    def weekday_name(day_of_week):
        """Return name of weekday.
        
            >>> weekday_name(1)
            'Sunday'
            
            >>> weekday_name(7)
            'Saturday'
            
        For days not between 1 and 7, return None
        
            >>> weekday_name(9)
            >>> weekday_name(0)
        """
        weekdays = ["Sunday",
                    "Monday",
                    "Tuesday",
                    "Wednesday",
                    "Thursday",
                    "Friday",
                    "Saturday"]
        return weekdays[(int(day_of_week) - 1) % 7]