杰瑞科技汇

Python contains怎么用?判断元素存在的方法有哪些?

Of course! This is a very common point of confusion for Python beginners because Python doesn't have a method called .contains().

Python contains怎么用?判断元素存在的方法有哪些?-图1
(图片来源网络,侵删)

The functionality you're looking for is provided by the in operator. Let's break it down.

The Short Answer: Use the in Operator

To check if an item exists in a collection (like a list, string, tuple, or dictionary), you use the in operator.

# --- Checking if a value exists in a list ---
my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
    print("Yes, 3 is in the list!")  # This will be printed
if 10 in my_list:
    print("No, this will not be printed.")
# --- Checking if a substring exists in a string ---
my_string = "Hello, World!"
if "World" in my_string:
    print("Yes, 'World' is in the string!") # This will be printed
if "Goodbye" in my_string:
    print("No, this will not be printed.")

Detailed Breakdown by Data Type

The behavior of in is slightly different depending on the type of data you're searching through.

For Lists, Tuples, and Sets

With these iterable types, in checks if the specified item exists anywhere in the collection.

Python contains怎么用?判断元素存在的方法有哪些?-图2
(图片来源网络,侵删)
# Lists
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)  # Output: True
print("grape" in fruits)   # Output: False
# Tuples
coordinates = (10.0, 20.0)
print(10.0 in coordinates) # Output: True
# Sets
unique_numbers = {1, 5, 8, 3}
print(5 in unique_numbers)  # Output: True

Performance Note: For large lists, checking for an item with in can be slow because Python has to search through the list one item at a time. For faster lookups, use a set (which is optimized for this).

For Strings

With strings, in checks if a specified substring exists within the string.

greeting = "Good morning, have a great day!"
print("morning" in greeting)   # Output: True
print("Great" in greeting)     # Output: False (case-sensitive)
print(" " in greeting)         # Output: True (checks for a space character)

For Dictionaries

When you use in with a dictionary, it checks for the existence of a key, not a value.

student = {
    "name": "Alice",
    "age": 25,
    "major": "Computer Science"
}
# Check for a key
print("name" in student)      # Output: True
print("major" in student)     # Output: True
# Check for a value (this is a common mistake!)
print("Alice" in student)     # Output: False
# To check for a value, you need to check in the dictionary's .values()
print("Alice" in student.values())  # Output: True
print(25 in student.values())      # Output: True

Why the Confusion with .contains()?

You might be thinking of .contains() because it exists in other programming languages like JavaScript (array.includes() or string.includes()) or Java (String.contains()).

Python chose to use a more universal and readable operator (in) instead of a method for this core operation.


The Exception: Pandas DataFrame

There is one very important exception where you do use a .contains() method: when working with Pandas DataFrames.

In Pandas, .contains() is a string method used to check for the presence of a substring within a column of strings.

# Make sure you have pandas installed: pip install pandas
import pandas as pd
data = {'Name': ['Alice Smith', 'Bob Johnson', 'Charlie Brown'],
        'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)
# Use the .str.contains() method on a column
# This returns a Series of boolean values (True/False)
in_ny = df['City'].str.contains('New')
print(in_ny)
# Output:
# 0     True
# 1    False
# 2    False
# Name: City, dtype: bool
# You can use this boolean Series to filter the DataFrame
people_in_ny = df[df['City'].str.contains('New')]
print("\nPeople in New York:")
print(people_in_ny)
# Output:
# People in New York:
#         Name       City
# 0  Alice Smith   New York

Summary Table

Data Type Method to Use Example Checks for...
List in operator if 'apple' in my_list: Item in the list
Tuple in operator if 10.0 in my_tuple: Item in the tuple
Set in operator if 5 in my_set: Item in the set
String in operator if 'world' in my_string: Substring in the string
Dictionary in operator if 'name' in my_dict: Key in the dictionary
Pandas Column .str.contains() df['col'].str.contains('text') Substring in the column's strings
分享:
扫描分享到社交APP
上一篇
下一篇