使用 Python 在数组列表中分离 0 和 1?


数组是一种线性数据结构,其元素存储在连续的内存地址中。它主要用于对相同数据类型的元素进行分组。

给定一个整数数组。根据文章“在数组中分离 0 和 1”,将数组分成两半,0 和 1。数组应该将所有 0 放置在左边,所有 1 放置在右边。

输入输出场景

让我们考虑一个输入及其输出场景,以在数组列表中分离 0 和 1 -

Input: [0,1,1,0,0,1,0,0,0]
Output: [0,0,0,0,0,0,1,1,1]

正如我们在输出中看到的,所有 0 和 1 都已在数组列表中分离,0 在左边,1 在右边。

在本文中,我们将讨论在 Python 中分离数组列表中 0 和 1 的各种方法。

通过计数 0 和 1

找到 0 的总数。计数将为 M。确定计数后,我们可以在数组的开头放置 M 个 0,并在剩余的 n – M 个位置放置 1。

示例

以下是一个使用计数 0 和 1 方法在数组列表中分离 0 和 1 的示例 -

Open Compiler
def segregating(array, x) : # Counting the 0's in array count = 0 for i in range(0, x) : if (array[i] == 0) : count = count + 1 # Loop for segregationg all the 0's for i in range(0, count) : array[i] = 0 # Loop for segregationg all the 1's for i in range(count, x) : array[i] = 1 # Function for printing the segregated array def print_the_array(array , x) : print( "The segregated array is :",end = "") for i in range(0, x) : print(array[i] , end = " ") # The driver function array = [0,1,1,0,0,1,0,0,0] x = len(array) segregating(array, x) print_the_array(array, x)

输出

以下是上述代码的输出 -

The segregated array is :0 0 0 0 0 0 1 1 1

使用 2 个索引进行遍历

Python 的 index() 函数返回给定列表中元素或字符串中字符的位置。

为了检查或使用数据作为过程的一部分,需要访问存储在数组中的每个元素(项)。这被称为遍历数组。

算法

以下是在使用 2 个索引遍历数组时分离数组列表中 0 和 1 的方法 -

  • 保留两个索引。将第一个索引设置为左边的 0,将第二个索引设置为右边的 n-1。

  • 向左或向右移动时遵循。

  • 只要有 0 可用,就继续增加左边的索引。

  • 只要有 1 可用,就继续减少右边的索引。

  • 如果 left < right,则交换 arr[left] 和 arr[right]。

示例

以下是在使用 2 个索引遍历数组时分离数组列表中 0 和 1 的示例 -

Open Compiler
def segregating(array, s): # Initializing both the left and the right index left, right = 0, s-1 while left < right: # Incrementing the left index while seeing 0 at the left while array[left] == 0 and left < right: left += 1 # Decrementing right index while seeing 1 at right while array[right] == 1 and left < right: right -= 1 if left < right: array[left] = 0 array[right] = 1 left += 1 right -= 1 return array # The driver code array = [0,1,1,0,0,1,0,0,0] array_size = len(array) print("The segregated array is :") print(segregating(array, array_size))

输出

以下是上述代码的输出 -

The segregated array is :
[0, 0, 0, 0, 0, 0, 1, 1, 1]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

使用列表推导式

列表推导式是 Python 中的常用技巧。在这里,我们应用此方法。我们从用户输入构建一个数组,并且每个条目都应该是 0 和 1 的随机组合。然后将左侧的 0 分组,右侧的 1 分组。我们遍历数组以分离两个不同的列表,一个包含 0,另一个包含 1,然后我们将这两个列表连接起来。

示例

以下是在使用列表推导式分离数组列表中 0 和 1 的示例 -

# Segregate all the 0's and 1's present in an array list def seg0s1s(A): n = ([i for i in A if i==0] + [i for i in A if i==1]) print(n) # Driver program if __name__ == "__main__": A=list() n=int(input("Enter the size of the array ::")) print("Enter the number ::") for i in range(int(n)): k=int(input("")) A.append(int(k)) print("The New ArrayList ::") seg0s1s(A)

输出

以下是上述代码的输出 -

Enter the size of the array ::7
Enter the number ::
1
0
1
0
0
1
1
The New ArrayList ::
[0, 0, 0, 1, 1, 1, 1]

更新于: 2022-12-19

1K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告