кажется, что существует некоторая путаница между словарем Python.Данные в массиве businesses
на самом деле являются строкой в нотации объектов JavaScript (JSON), и python видит ее как строку.Чтобы использовать его в качестве словаря Python, вам необходимо преобразовать его, используя библиотеку Python json
.Преобразование будет выглядеть примерно так:
import json
python_obj = json.loads(json_str)
Предоставленный вами объект представляет собой массив строк JSON, например
businesses = ["{\"hours\":"
"{"
"\"tuesday\": [[\"11:30\", \"23:00\"]],"
"\"thursday\": [[\"11:30\", \"23:00\"]],"
"\"wednesday\": [[\"11:30\", \"23:00\"]],"
"\"friday\": [[\"11:30\", \"23:00\"]],"
"\"sunday\": [[\"9:00\", \"23:00\"]],"
"\"monday\": [[\"11:30\", \"23:00\"]],"
"\"saturday\": [[\"11:30\", \"23:00\"]]"
"},"
"\"name\": \"XYZ\""
"}"]
Массив словаря Python будет выглядеть следующим образом
businesses = [
{
"hours":{
"tuesday":[["11:30","23:00"]],
"thursday":[["11:30","23:00"]],
"wednesday":[["11:30","23:00"]],
"friday":[["11:30", "23:00"]],
"sunday":[["9:00", "23:00"]],
"monday":[["11:30", "23:00"]],
"saturday":[["11:30", "23:00"]]
},
"name":"XYZ"
}
]
Итак, причина, по которой вы видите вывод каждой буквы, заключается в том, что вы перебираете строку, а не словарь Python.Когда python просматривает строку, он просматривает каждый символ.Точно так же, как показано ниже.
string_data = "123456789"
# will iterate through each character
for i in string_data:
print(i) # will print 9 times each time outputting a character in order
Что касается функции, вам необходимо убедиться, что при выполнении ваших временных сравнений вы используете объекты времени Python вместо строк, так как это будет точно сравнивать время.Я не совсем уверен, почему времена указаны во вложенном массиве, таком как [["11:30","23:00"]]
, и поэтому вам, вероятно, потребуется изменить следующую функцию, если данные отформатированы для других предприятий.
Этофункция, которая описывает то, что вам нужно.
import json, datetime
businesses = ["{\"hours\":"
"{"
"\"tuesday\": [[\"11:30\", \"23:00\"]],"
"\"thursday\": [[\"11:30\", \"23:00\"]],"
"\"wednesday\": [[\"11:30\", \"23:00\"]],"
"\"friday\": [[\"11:30\", \"23:00\"]],"
"\"sunday\": [[\"9:00\", \"23:00\"]],"
"\"monday\": [[\"11:30\", \"23:00\"]],"
"\"saturday\": [[\"11:30\", \"23:00\"]]"
"},"
"\"name\": \"XYZ\""
"}"]
def count_businesses(business_list):
"""
:param business_list: An array of business in JSON to query from
:return: Int of the count of businesses that are open on Sunday before 10 am
"""
# initialize the array that will contain the businesses that meet the search criteria
businesses_found = []
# python time object of 10:00am that will be used to check against
opening_business_time = datetime.time(hour=10)
# iterate through each busineses to check if it meets the search criteria
for business in business_list:
# since each business is in JSON, we convert it into a Python object
business_obj = json.loads(business)
# Look into the 'hours' key, then the 'sunday' key and get the first item in the array. ( i.e ["11:30","23:00"])
sunday_hours = business_obj["hours"]["sunday"][0]
# read in the sunday opening hours as a string from the first value of the array. {i.e "11:30")
sunday_opening_hours_str = sunday_hours[0]
# convert the sunday opening hours into a time object so it can be compared.
# '%H:%M' looks for the format HH:MM in a string.
# for more reference. https://docs.python.org/3.6/library/datetime.html#strftime-and-strptime-behavior
sunday_opening_hours_time = datetime.datetime.strptime(sunday_opening_hours_str, '%H:%M').time()
# if sunday opening hours is before 10 am
if sunday_opening_hours_time < opening_business_time:
# add the business object to the list
businesses_found.append(business_obj)
# returns the count of the businesses that met the search criteria
return len(businesses_found)
total = count_businesses(businesses)
print(total)