如何检查列表两元素存在性?如何校验列表指定元素先后顺序?
Hey there! Let's break down your two Python list questions with practical, easy-to-use solutions:
There are a few straightforward ways to handle this, depending on your specific needs:
Simple membership check
The most direct approach is to verify both elements exist in the list. This works great for two elements, and scales easily if you need to check more later:def contains_both(lst, elem_a, elem_b): # Basic check for two elements return elem_a in lst and elem_b in lst # Or use all() for a dynamic list of elements # return all(item in lst for item in [elem_a, elem_b])Example usage:
sample_list = ["apple", "banana", "cherry"] print(contains_both(sample_list, "banana", "apple")) # Output: True print(contains_both(sample_list, "date", "apple")) # Output: FalseSet subset validation
Converting your list and target elements to sets lets you use clean set operations to validate membership. This is especially handy if you're working with multiple elements:def contains_both(lst, elem_a, elem_b): target_elements = {elem_a, elem_b} return target_elements.issubset(set(lst))
⚠️ Quick note: If your list might have duplicate elements and you need to ensure at least one occurrence of each, both methods above work perfectly. If you need to check for specific counts (e.g., at least two of elem_a), add a check like lst.count(elem_a) >= 2 instead.
Your original code only checks if both stations exist, not their order—so let's fix that by validating their positions in the list.
Solution 1: Using index positions (for unique elements)
If each station appears only once in your list, you can grab their indices and compare them directly. We'll also add checks for missing stations to avoid errors:
listOfStations = ['FSTL40503', 'LHSL40503', 'WEHL40503', 'BKGL40503', 'DDKL40503', 'RNML40503', 'PFLL40503', 'GRYL40503'] required_first = 'FSTL40503' required_second = 'PFLL40503' # First confirm both stations exist if required_first in listOfStations and required_second in listOfStations: # Get their positions in the list idx_first = listOfStations.index(required_first) idx_second = listOfStations.index(required_second) if idx_first < idx_second: print("Both stations found in the correct order!") else: print("Stations exist but are in the wrong order.") else: print("One or both stations are missing from the list.")
Solution 2: Handling duplicate elements
If your list might have multiple instances of the same station (e.g., multiple FSTL40503 entries), use a traversal approach to check if any occurrence of the first station comes before any occurrence of the second:
def check_correct_order(lst, first_elem, second_elem): seen_first = False for item in lst: if item == first_elem: seen_first = True # If we've already seen the first element and now hit the second, we're good elif item == second_elem and seen_first: return True # If we finish the loop without finding the correct sequence return False # Test it out if check_correct_order(listOfStations, required_first, required_second): print("Correct order verified!") else: print("Stations are missing or in the wrong order.")
This traversal method is more robust for lists with duplicates—it will return True even if there are extra instances of either station later in the list.
内容的提问来源于stack exchange,提问作者Gray Ridley

