杰瑞科技汇

Python如何创建数组?

Of course! In Python, the term "array" can mean a few different things. The most common and recommended way is to use a list. For more advanced numerical work, you'll use the NumPy library.

Python如何创建数组?-图1
(图片来源网络,侵删)

Here's a complete guide covering the main ways to create arrays in Python.


The Most Common Way: Python Lists

A list is the built-in, fundamental data structure for ordered, mutable (changeable) collections in Python. It's the closest equivalent to a simple array in other languages.

Creating a Basic List

You create a list by placing comma-separated values inside square brackets [].

# An empty list
empty_list = []
print(f"Empty list: {empty_list}")
# A list of integers
numbers = [1, 5, 12, 34, 88]
print(f"List of numbers: {numbers}")
# A list of strings
fruits = ["apple", "banana", "cherry"]
print(f"List of fruits: {fruits}")
# A list with mixed data types (lists can hold anything)
mixed_data = [10, "hello", 3.14, True]
print(f"Mixed data list: {mixed_data}")

Creating a List with a Specific Size (Filled with a Value)

If you need a list of a certain size initialized with a default value (like 0), you can use a list comprehension or the operator.

Python如何创建数组?-图2
(图片来源网络,侵删)
# Method 1: List Comprehension (very common and readable)
size = 5
list_of_zeros = [0] * size
print(f"List of 5 zeros: {list_of_zeros}")
list_of_empty_strings = [""] * size
print(f"List of 5 empty strings: {list_of_empty_strings}")
# Method 2: Using a for loop (more verbose)
list_of_ones = []
for i in range(size):
    list_of_ones.append(1)
print(f"List of 5 ones: {list_of_ones}")
# Method 3: List Comprehension (more flexible)
list_of_twos = [2 for i in range(size)]
print(f"List of 5 twos: {list_of_twos}")

The Powerful Way: NumPy Arrays

For any serious numerical, scientific, or data analysis work, you should use the NumPy library. NumPy provides a high-performance multidimensional array object and tools for working with these arrays.

First, you need to install it:

pip install numpy

Then, you can import it and create arrays.

Creating a NumPy Array

import numpy as np
# Create an array from a Python list
python_list = [1, 2, 3, 4, 5]
np_array_from_list = np.array(python_list)
print(f"NumPy array from list: {np_array_from_list}")
print(f"Type: {type(np_array_from_list)}")
# Create an array of zeros
zeros_array = np.zeros(5)  # Creates a 1D array with 5 zeros
print(f"\nArray of 5 zeros: {zeros_array}")
# Create an array of ones
ones_array = np.ones(4) # Creates a 1D array with 4 ones
print(f"Array of 4 ones: {ones_array}")
# Create an array filled with a specific value
filled_array = np.full(6, 9) # Creates a 1D array with 6 elements, all 9
print(f"Array of 6 nines: {filled_array}")
# Create a sequence of numbers (like Python's range)
# np.arange(start, stop, step)
sequence_array = np.arange(0, 10, 2) # 0 to 9 (exclusive), stepping by 2
print(f"Sequence array (0 to 10, step 2): {sequence_array}")
# Create an array with evenly spaced numbers over an interval
# np.linspace(start, stop, num_elements)
linspace_array = np.linspace(0, 1, 5) # 5 numbers from 0 to 1 (inclusive)
print(f"Linspace array (0 to 1, 5 elements): {linspace_array}")
# Create a 2D array (matrix)
# We pass a list of lists to np.array()
matrix_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(f"\n2D Array (Matrix):\n{matrix_2d}")
# Create a 2D array of zeros
zeros_2d = np.zeros((3, 4)) # 3 rows, 4 columns
print(f"\n2D Array of zeros (3x4):\n{zeros_2d}")

Specialized Arrays: The array Module

Python has a built-in array module that creates more memory-efficient arrays than lists, but it's less flexible because all elements must be of the same type. It's rarely used in favor of NumPy.

import array
# The first argument is the 'type code' (e.g., 'i' for int, 'f' for float)
# The second argument is the initial data from the list.
int_array = array.array('i', [1, 2, 3, 4, 5])
print(f"Built-in array module: {int_array}")
print(f"Type: {type(int_array)}")
# You cannot add a string to an 'i' (integer) type array
# This will cause a TypeError:
# int_array.append("hello") 
Feature Python List NumPy Array array Module
Flexibility High: Can hold mixed data types. Low: All elements must be the same type. Low: All elements must be the same type (specified at creation).
Performance Slower for large numerical operations. Very Fast: Optimized for math and large datasets. Faster than lists, but slower than NumPy.
Functionality Basic collection methods. Rich with math, linear algebra, and statistical functions. Basic array operations.
Use Case General-purpose, everyday programming. Scientific computing, data science, machine learning. Niche use cases where memory is extremely constrained.

Summary: Which One Should I Use?

  • For general-purpose programming: Use a Python List. It's simple, flexible, and perfect for most tasks.
    my_data = [10, "user", 3.14]
  • For numerical, scientific, or data analysis tasks: Use NumPy. It's the standard in the Python scientific world.
    import numpy as np
    my_data = np.array([10, 20, 30, 40])
  • Almost never use the built-in array module unless you have a very specific reason related to memory efficiency and are not using NumPy.
分享:
扫描分享到社交APP
上一篇
下一篇