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] 
相关推荐
布林模型16 分钟前
缠论工具czsc快速使用入门(二)
python·缠论·快速入门·czsc
邂逅you31 分钟前
用python操作mysql之pymysql库基本操作
数据库·python·mysql
啊森要自信33 分钟前
【GUI自动化测试】YAML 配置文件应用:从语法解析到 Python 读写
android·python·缓存·pytest·pip·dash
勤奋菲菲36 分钟前
Vue3+Three.js:requestAnimationFrame的详细介绍
开发语言·javascript·three.js·前端可视化
合作小小程序员小小店43 分钟前
web开发,学院培养计划系统,基于Python,FlaskWeb,Mysql数据库
后端·python·mysql·django·web app
要天天开心啊1 小时前
Java序列化和反序列化
java·开发语言
渣渣盟1 小时前
解密NLP:从入门到精通
人工智能·python·nlp
老程序员刘飞1 小时前
注册 区块链节点
python
KAIWEILIUCC1 小时前
Python抽象基类(abc.ABC)介绍
python
二宝1521 小时前
黑马商城day1-MyBatis-Plus
java·开发语言·mybatis