杰瑞科技汇

Python列表如何判断元素是否包含?

Of course! The phrase "Python contains list" can mean a few different things. I'll cover the most common interpretations, from the simplest check to more complex searches.

Python列表如何判断元素是否包含?-图1
(图片来源网络,侵删)

Checking if a List Contains a Specific Value (The in Operator)

This is the most common and direct meaning. You want to know if a single value exists within a list.

The best tool for this is the in operator. It returns True if the value is found and False if it is not.

Basic Example

# Our list of fruits
fruits = ['apple', 'banana', 'cherry', 'orange']
# Check if 'cherry' is in the list
is_cherry_present = 'cherry' in fruits
print(f"Is 'cherry' in the list? {is_cherry_present}")  # Output: Is 'cherry' in the list? True
# Check if 'grape' is in the list
is_grape_present = 'grape' in fruits
print(f"Is 'grape' in the list? {is_grape_present}")   # Output: Is 'grape' in the list? False

Common Use Case: if Statements

You can use the in operator directly inside an if statement to control program flow.

fruits = ['apple', 'banana', 'cherry', 'orange']
user_fruit = input("Enter a fruit to check: ")
if user_fruit in fruits:
    print(f"Yes, {user_fruit} is in our inventory!")
else:
    print(f"Sorry, we don't have {user_fruit}.")
# Example interaction:
# Enter a fruit to check: banana
# Yes, banana is in our inventory!

Checking if a List Contains Another List (Sub-list)

Sometimes you want to check if one list is a contiguous sequence within another list.

Python列表如何判断元素是否包含?-图2
(图片来源网络,侵删)

The in operator works for this too!

Example

main_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sub_list_1 = [4, 5, 6]
sub_list_2 = [5, 6, 7, 8]
sub_list_3 = [2, 4] # Not contiguous
print(f"Is {sub_list_1} in {main_list}? {sub_list_1 in main_list}")
# Output: Is [4, 5, 6] in [1, 2, 3, 4, 5, 6, 7, 8, 9]? True
print(f"Is {sub_list_2} in {main_list}? {sub_list_2 in main_list}")
# Output: Is [5, 6, 7, 8] in [1, 2, 3, 4, 5, 6, 7, 8, 9]? True
print(f"Is {sub_list_3} in {main_list}? {sub_list_3 in main_list}")
# Output: Is [2, 4] in [1, 2, 3, 4, 5, 6, 7, 8, 9]? False

Checking if a List Contains a Value (The Alternative: .count() Method)

If you need to know how many times a value appears, you can use the .count() method. It returns the number of occurrences. You can then check if this count is greater than zero.

Example

grades = ['A', 'B', 'C', 'A', 'D', 'B', 'A']
# Count the number of 'A's
count_of_a = grades.count('A')
print(f"The grade 'A' appears {count_of_a} times.") # Output: The grade 'A' appears 3 times.
# Check if 'C' is present by checking its count
is_c_present = grades.count('C') > 0
print(f"Is 'C' present? {is_c_present}") # Output: Is 'C' present? True
# Check if 'F' is present
is_f_present = grades.count('F') > 0
print(f"Is 'F' present? {is_f_present}") # Output: Is 'F' present? False

Why prefer in over .count() for a simple check?

  • Performance: The in operator stops searching as soon as it finds a match. The .count() method will always iterate through the entire list to count all occurrences. For a simple "is it there or not?" check, in is more efficient.
  • Readability: if 'A' in grades: is more direct and easier to read than if grades.count('A') > 0:.

Checking for Multiple Values (Any of them)

What if you want to check if a list contains any of a set of values?

Python列表如何判断元素是否包含?-图3
(图片来源网络,侵删)

You can do this by combining in with a for loop or, more elegantly, with a generator expression and the built-in any() function.

Example with any() and a Generator Expression

This is the most "Pythonic" and efficient way.

tasks = ['write report', 'send email', 'fix bug', 'plan meeting']
# Check if any of these keywords are in the tasks list
keywords_to_find = ['urgent', 'fix', 'meeting']
# The any() function returns True if any element in the iterable is true.
# The generator expression checks each keyword.
is_urgent_or_fix_or_meeting_present = any(keyword in tasks for keyword in keywords_to_find)
print(f"Is any keyword present? {is_urgent_or_fix_or_meeting_present}")
# Output: Is any keyword present? True

Example with a for loop (More Verbose)

This achieves the same result but is more lines of code.

tasks = ['write report', 'send email', 'fix bug', 'plan meeting']
keywords_to_find = ['urgent', 'fix', 'meeting']
found = False
for keyword in keywords_to_find:
    if keyword in tasks:
        found = True
        break # Exit the loop as soon as we find a match
print(f"Is any keyword present? {found}")
# Output: Is any keyword present? True

Checking if a List Contains a Specific Data Type

Sometimes you might want to know if a list has at least one item of a certain type (e.g., an integer, a string, a dictionary).

The best way is to use a for loop with the isinstance() function.

Example

mixed_data = [10, 'hello', 3.14, {'name': 'Alice'}, [1, 2, 3]]
# Check if the list contains any integers
has_integer = any(isinstance(item, int) for item in mixed_data)
print(f"Does the list contain an integer? {has_integer}") # Output: True
# Check if the list contains any strings
has_string = any(isinstance(item, str) for item in mixed_data)
print(f"Does the list contain a string? {has_string}") # Output: True
# Check if the list contains any tuples
has_tuple = any(isinstance(item, tuple) for item in mixed_data)
print(f"Does the list contain a tuple? {has_tuple}") # Output: False

Summary Table

Goal Best Method Example
Check for a single value in operator if 'apple' in fruits:
Check for a sub-list in operator if [4, 5] in my_list:
Get the count of a value .count() method count = my_list.count('A')
Check if any of several values exist any() with a generator expression any(k in my_list for k in ['a', 'b'])
Check for a specific data type any() with isinstance() in a generator any(isinstance(x, str) for x in my_list)
分享:
扫描分享到社交APP
上一篇
下一篇