如何在包含range的Python列表中查找指定值?
Hey there! Let's break down why your current code isn't working and get it sorted out.
The Problem with Your Original Code
Your code tries to check if (5,12) is in the list, but the list contains (5, range(10,15))—these are not the same thing. Python's in operator does a strict equality check: it compares the entire tuple, and since one has an integer as the second element and the other has a range object, it can't find a match. Also, a couple of syntax issues: you shouldn't use list as a variable name (it overwrites Python's built-in list type), and Print should be lowercase print.
The Correct Approach
We need to check two conditions for each tuple in the list:
- The first element of the tuple matches your target's first value (5 in this case)
- Your target's second value (12) is contained within the
rangeobject in the tuple's second position
Solution Code Examples
First, properly set up your list (avoid using list as a variable name):
# Initialize your list with a descriptive name my_list = [] # Add the tuple containing a range my_list.append((5, range(10, 15)))
Option 1: Explicit Loop
This is straightforward and easy to follow:
target = (5, 12) is_found = False for item in my_list: # Check both conditions: matching first element, and value in range if item[0] == target[0] and target[1] in item[1]: is_found = True break if is_found: print("yes") else: print("no")
Option 2: Concise any() Function
For a more compact solution, use Python's any() function, which returns True if any element in the iterable meets the condition:
target = (5, 12) if any(item[0] == target[0] and target[1] in item[1] for item in my_list): print("yes") else: print("no")
Both of these will correctly detect that 12 is within range(10,15) and that the first element matches 5, so they'll print "yes" as expected.
内容的提问来源于stack exchange,提问作者Alberto Pani

