杰瑞科技汇

python array resize

Of course! In Python, the concept of "resizing an array" can mean a few different things depending on the data structure you're using. There isn't a single .resize() method that works for all, so let's break it down by the most common array-like structures.

python array resize-图1
(图片来源网络,侵删)

Summary: Which One Should I Use?

Data Structure How to "Resize" Best For...
list Slicing & Reassignment
my_list = new_bigger_list
General-purpose use. The most Pythonic and flexible way.
array.array .fromlist() or .extend() Storing homogeneous data types (like numbers) with less memory than a list.
numpy.ndarray .resize() method Numerical and scientific computing. Highly efficient for large datasets.
bytearray Slicing & Reassignment Mutable sequences of bytes.

Python's Built-in list (Most Common)

Python's list is the most flexible and commonly used "array." Crucially, a list is a dynamic array, meaning it automatically grows and shrinks as you add or remove items. You don't need to manually resize it for basic operations.

However, if you need to explicitly create a new list of a specific size (e.g., filled with zeros), you can do it easily.

To Create a New, Larger List

The most Pythonic way is to use list multiplication.

# Original list
my_list = [1, 2, 3]
print(f"Original: {my_list}")
# Create a new list with 5 elements, all initialized to 0
new_size = 5
new_list = [0] * new_size
print(f"New list (size {new_size}): {new_list}")
# Now, you can copy your old data into the new list
# (This is a manual process, lists don't have a built-in "copy and pad" function)
for i in range(len(my_list)):
    new_list[i] = my_list[i]
print(f"Resized list: {new_list}")

Output:

python array resize-图2
(图片来源网络,侵删)
Original: [1, 2, 3]
New list (size 5): [0, 0, 0, 0, 0]
Resized list: [1, 2, 3, 0, 0]

To Create a New, Smaller List

This is straightforward with slicing.

# Original list
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print(f"Original: {my_list}")
# Resize to a smaller list (e.g., keep only the first 4 elements)
new_size = 4
new_list = my_list[:new_size] # Slice from the beginning to the new size
print(f"Resized list (size {new_size}): {new_list}")

Output:

Original: [1, 2, 3, 4, 5, 6, 7, 8]
Resized list (size 4): [1, 2, 3, 4]

The array Module

The array module provides a more memory-efficient way to store C-style arrays. It's less flexible than a list because it can only hold elements of a single data type.

It does not have a .resize() method. You have to use other methods to change its size.

python array resize-图3
(图片来源网络,侵删)

To Grow an array

You can use the .fromlist() or .extend() methods.

import array
# Original array of integers
my_array = array.array('i', [10, 20, 30])
print(f"Original: {my_array}")
# Create a new list to add
elements_to_add = [40, 50, 60]
# Option 1: Use .extend() with another array or iterable
my_array.extend(array.array('i', elements_to_add))
print(f"After extend(): {my_array}")
# Option 2: Create a new list and convert the whole array
# This is less efficient but works
new_array_data = my_array.tolist() + [70, 80]
my_array = array.array('i', new_array_data)
print(f"After tolist() and re-creation: {my_array}")

Output:

Original: array('i', [10, 20, 30])
After extend(): array('i', [10, 20, 30, 40, 50, 60])
After tolist() and re-creation: array('i', [10, 20, 30, 40, 50, 60, 70, 80])

To Shrink an array

You can use slicing to create a new array.

import array
# Original array
my_array = array.array('i', [10, 20, 30, 40, 50])
print(f"Original: {my_array}")
# Resize to a smaller array (e.g., keep only the first 3 elements)
new_size = 3
my_array = my_array[:new_size]
print(f"Resized array (size {new_size}): {my_array}")

Output:

Original: array('i', [10, 20, 30, 40, 50])
Resized array (size 3): array('i', [10, 20, 30])

The NumPy Array (Best for Numerics)

If you are doing any kind of numerical, scientific, or data analysis work, you should be using NumPy. NumPy's ndarray is highly optimized and has a built-in .resize() method that modifies the array in-place.

Using the .resize() Method

This method modifies the array directly. If the new size is larger, it fills the extra space with repeated copies of the original array (this is called "repeating"). If it's smaller, it truncates the array.

import numpy as np
# Original NumPy array
arr = np.array([1, 2, 3, 4])
print(f"Original array:\n{arr}\n")
# Resize to a larger size (8 elements)
# It will repeat the original array to fill the space
arr.resize(8)
print(f"Resized to 8 elements (in-place):\n{arr}\n")
# Resize to a smaller size (3 elements)
# It will truncate the array from the end
arr.resize(3)
print(f"Resized to 3 elements (in-place):\n{arr}\n")
# To avoid the repeating behavior, use np.pad or np.resize
arr = np.array([1, 2, 3, 4])
new_arr = np.pad(arr, (0, 4), 'constant', constant_values=0)
print("Resized to 8 elements using np.pad (no repeating):\n", new_arr)

Output:

Original array:
[1 2 3 4]
Resized to 8 elements (in-place):
[1 2 3 4 1 2 3 4]
Resized to 3 elements (in-place):
[1 2 3]
Resized to 8 elements using np.pad (no repeating):
 [1 2 3 4 0 0 0 0]

The bytearray

A bytearray is a mutable sequence of bytes. It behaves very similarly to a list of integers in the range 0-255. You resize it using slicing and reassignment, just like a list.

# Original bytearray
my_ba = bytearray(b'hello world')
print(f"Original: {my_ba}")
# Resize to a larger size (add null bytes b'\x00')
new_size = 20
# Create a new bytearray with the new size filled with zeros
new_ba = bytearray(new_size)
# Copy the original data into the new bytearray
new_ba[:len(my_ba)] = my_ba
print(f"Resized to {new_size} bytes: {new_ba}")
# Resize to a smaller size (truncate)
new_size = 5
my_ba = my_ba[:new_size]
print(f"Resized to {new_size} bytes: {my_ba}")

Output:

Original: bytearray(b'hello world')
Resized to 20 bytes: bytearray(b'hello world\x00\x00\x00\x00\x00\x00\x00\x00\x00')
Resized to 5 bytes: bytearray(b'hello')

Conclusion

  • For general-purpose programming, use Python's built-in list. It's dynamic, flexible, and the "Pythonic" way to handle sequences.
  • For numerical computing, always use NumPy. Its .resize() method is fast and efficient, and its arrays are the standard for data science in Python.
  • For memory-efficient storage of homogeneous data (like a large block of numbers), the array.array module is a good choice, but you'll need to use its methods like .extend() or slicing to resize it.
分享:
扫描分享到社交APP
上一篇
下一篇