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] 
相关推荐
Thneonl2 小时前
Celery 生产踩坑:1000 任务积压与 acks_late 双重执行
后端·python
清桔2 小时前
模型的调用
python
小小张说故事2 小时前
Python 多线程为什么跑不快?asyncio 入门指南:异步并发从零上手
后端·python
10年前端老司机2 小时前
干货分享|企业智能知识库 Rerank 重排序落地实践与踩坑总结
python·aigc·agent
天天被压力2 小时前
【Python 量化取数指南 #13】Python 把行情落库:sqlite 一键存,回测随用随取
java·人工智能·python
天天被压力2 小时前
【Python 量化取数指南 #14】Python 清洗行情数据:复权停牌对齐,回测不翻车
java·人工智能·python
Python私教2 小时前
Python环境配置:conda+PyCharm+换源,附6个坑
人工智能·python·pycharm
databook2 小时前
检测数据异常值的五种统计技术
python·数据挖掘·数据分析
小小张说故事2 小时前
Selenium 装驱动太麻烦?Playwright 入门指南:Python 网页自动化新标准
python
海宇数科2 小时前
Python数据工程:利用海宇车型识别精准优化车险理赔合规体验
人工智能·python