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] 
相关推荐
superman超哥2 分钟前
Rust 错误处理模式:Result、?运算符与 anyhow 的最佳实践
开发语言·后端·rust·运算符·anyhow·rust 错误处理
lly2024062 分钟前
Web 品质样式表
开发语言
Wang's Blog3 分钟前
Nodejs-HardCore: 模块管理与I/O操作详解
开发语言·nodejs
微爱帮监所写信寄信3 分钟前
微爱帮监狱寄信写信小程序PHP底层优化框架
java·开发语言·数据库·spring·微信·php·mybatis
lly2024066 分钟前
R 语言注释指南
开发语言
2401_8414956411 分钟前
【游戏开发】坦克大战
python·游戏·socket·pygame·tkinter·pyinstaller·坦克大战
liu****12 分钟前
04_Pandas数据分析入门
python·jupyter·数据挖掘·数据分析·numpy·pandas·python常用工具
bigHead-12 分钟前
前端双屏显示与通信
开发语言·前端·javascript
richxu2025100117 分钟前
Java是当今最优雅的开发语言
java·开发语言