python-list-comprehension-segregate-0s-1s-array-list

Python 列表理解|在数组列表中分隔 0 和 1

原文:https://www . geesforgeks . org/python-list-intensity-separate-0s-1s-array-list/

给你一个随机排列的 0 和 1 的数组。将阵列左侧的 0 和右侧的 1 分开。

示例:

py 复制代码
Input  :  arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] 
Output :  [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] 

对于这个问题我们已经有了解决方案,请参考在一个数组链接中分隔 0 和 1。我们可以使用列表理解在 Python 中快速解决这个问题。遍历给定的列表,分离出两个不同的列表,一个包含所有 0,另一个包含所有 1。现在将这两个列表连接在一起。

py 复制代码
# Function to Segregate 0's and 1's in an array list

def segregate(arr):
    res = ([x for x in arr if x==0] + [x for x in arr if x==1])
    print(res)

# Driver program
if __name__ == "__main__":
    arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] 
    segregate(arr)

输出:

py 复制代码
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1] 
相关推荐
C+-C资深大佬20 分钟前
C++数据类型
开发语言·c++·算法
ID_1800790547325 分钟前
日本乐天商品详情API接口的请求构造与参数说明
开发语言·python·pandas
派大鑫wink32 分钟前
【Day34】Servlet 进阶:会话管理(Cookie vs Session)
java·开发语言·学习方法
多米Domi01136 分钟前
0x3f 第35天 电脑硬盘坏了 +二叉树直径,将有序数组转换为二叉搜索树
java·数据结构·python·算法·leetcode·链表
猫天意1 小时前
【深度学习小课堂】| torch | 升维打击还是原位拼接?深度解码 PyTorch 中 stack 与 cat 的几何奥义
开发语言·人工智能·pytorch·深度学习·神经网络·yolo·机器学习
crossaspeed1 小时前
Java-线程池(八股)
java·开发语言
UR的出不克2 小时前
使用 Python 爬取 Bilibili 弹幕数据并导出 Excel
java·python·excel
niaiheni2 小时前
PHP文件包含
开发语言·php
初次见面我叫泰隆2 小时前
Qt——1、初识Qt
开发语言·c++·qt
Arms2062 小时前
python时区库学习
开发语言·python·学习