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] 
相关推荐
qq_161111271 天前
Jenkins+Python自动化测试持续集成详细教程
自动化测试·python·jenkins·教程·持续集成
爱吃苹果的梨叔1 天前
训练集群网络中断怎么办?智算机房的 Console 串口排障方案
网络·python·智能路由器·php
李妍.1 天前
02Numpy基础(上)
开发语言·python
TheBestRucy1 天前
Python 九阳神功之贰:面向对象(下)
开发语言·python
2601_965958461 天前
口腔黏膜脱皮超2周未愈建议及时就医
人工智能·python
AI_小站1 天前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
微小冷1 天前
在不同空间中展示数据(欧式、球面、庞加莱圆盘)
python·双曲空间·微分几何·geomstats·庞加莱圆盘·球面
felixking1 天前
C++20 协程
开发语言·c++·协程
weixin_431600441 天前
Agent Workflow 学习向:Code 节点,比模板更强的变量加工
后端·python·学习·ai·
讲温控就好了1 天前
从医疗影像到能源存储——芯片冷却温控技术的跨行业赋能
人工智能·python·能源