Python中如何验证元组元素是否存在于元组列表并获取对应元组其他元素
Let's break down what you're trying to do and fix the issue with your current code.
Your Goal
You want to check if the element at index 3 of your validate tuple ('456456') exists in any tuple within the db list. If it does, you want to print the other elements from that matching tuple.
Why Your Current Code Isn't Working
Looking at your code:
val1 = [] val = validate[3] val1.append(val) print(val1) if (any(val1 in i for i in db)) : print('item exists') else: print('item does not exists')
The problem is that you're wrapping your target value ('456456') into a list (val1 = ['456456']), then checking if that list is an element of any tuple in db. But every element in the db tuples is a string, not a list—so this condition will never be true. You need to check for the string itself, not a list containing it.
Fixed Solutions
Solution 1: Iterate Through the List (Clear & Explicit)
This approach loops through each tuple in db, checks if your target exists, and prints the matching tuple's other elements once found:
validate = ('1', 'green', '14:54:54:65:66:89', '456456', '2') db = [('456456', 'rajat', 'rajat@gmail.com', '8764285479'), ('123456', 'rahul', 'rahul@gmail.com', '32478524785')] # Extract the value we need to search for target = validate[3] found = False for tuple_in_db in db: if target in tuple_in_db: print(f"Success! Found the target in this tuple: {tuple_in_db}") # Get all elements except the target value other_elements = [elem for elem in tuple_in_db if elem != target] print(f"Other elements in the matching tuple: {other_elements}") found = True break # Remove this line if you want to find ALL matching tuples, not just the first if not found: print("Item does not exist in the database.")
Solution 2: Use next() for a Concise Approach
If you only care about the first matching tuple, you can use Python's next() function with a generator expression. This is more compact:
validate = ('1', 'green', '14:54:54:65:66:89', '456456', '2') db = [('456456', 'rajat', 'rajat@gmail.com', '8764285479'), ('123456', 'rahul', 'rahul@gmail.com', '32478524785')] target = validate[3] try: matching_tuple = next(t for t in db if target in t) print(f"Found matching tuple: {matching_tuple}") other_elements = [elem for elem in matching_tuple if elem != target] print(f"Other elements: {other_elements}") except StopIteration: print("Item does not exist in the database.")
Key Notes
- Both solutions directly check if
target(the string'456456') is present in each tuple, which is the correct condition. - The list comprehension
[elem for elem in tuple_in_db if elem != target]filters out the target value to give you the other elements. If your tuple might have duplicate instances of the target, this will remove all of them—adjust if needed.
内容的提问来源于stack exchange,提问作者rajat maan

