Python 将数组中的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的示例 –
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()函数可以返回给定列表中元素的位置或字符串中的字符。
为了检查或使用数据作为过程的一部分,需要访问存储在数组中的每个元素(项)。这被称为通过数组遍历。
步骤
以下是一种使用两个索引通过数组遍历来将0和1分离的方法:
- 保持两个索引。将左侧的第一个索引设置为0,将右侧的第二个索引设置为n-1。
-
向左或向右移动时遵循以下步骤。
-
当有可用的0时,增加左侧索引。
-
当有可用的1时,继续减小右侧索引。
-
如果左侧索引小于右侧索引,则交换arr[left]和arr[right]。
示例
以下是使用两个索引通过数组遍历来将0和1分离的示例:
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]
使用列表推导式
一种常见的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]