遍历字典及内部列表:查找全False的Bay与状态检测需求
Got it, let's tackle this step by step. First, let's assume we have a sample dictionary representing bay booking statuses to work with:
bay_status = { 'Bay1': [True, False, True], 'Bay2': [True, True, False], 'Bay3': [False, True, False], 'Bay4': [False, False, False] }
1. Find Bays with All Unbooked Slots (All False)
To identify bays where every slot is unbooked (all elements in the list are False), we can iterate through the dictionary and use Python's all() function to check each bay's slot list.
Here's the code:
# Initialize a list to hold fully unbooked bays empty_bays = [] # Iterate over each bay and its slot statuses for bay_name, slots in bay_status.items(): # Check if all slots are False (unbooked) if all(not slot for slot in slots): empty_bays.append(bay_name) print("Fully unbooked Bays:", empty_bays) # Output: ['Bay4']
How this works: The all(not slot for slot in slots) expression checks that every slot in the list is False (since not False evaluates to True, and all() returns True only if all elements in the iterable are True).
2. Check Individual Slot Booking Statuses for Each Bay
To get a clear breakdown of every slot's booking status in each bay, we can use nested loops: one to iterate over each bay, and another to loop through each slot (with its index for clarity).
Here's the implementation:
# Loop through each bay to display slot statuses for bay_name, slots in bay_status.items(): print(f"\n--- {bay_name} Booking Status ---") # Use enumerate to get slot index (starting at 1 for readability) for slot_number, is_booked in enumerate(slots, start=1): status = "Booked" if is_booked else "Unbooked" print(f"Slot {slot_number}: {status}")
Sample Output:
--- Bay1 Booking Status --- Slot 1: Booked Slot 2: Unbooked Slot 3: Booked --- Bay2 Booking Status --- Slot 1: Booked Slot 2: Booked Slot 3: Unbooked --- Bay3 Booking Status --- Slot 1: Unbooked Slot 2: Booked Slot 3: Unbooked --- Bay4 Booking Status --- Slot 1: Unbooked Slot 2: Unbooked Slot 3: Unbooked
内容的提问来源于stack exchange,提问作者abdallah

