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] 
相关推荐
一方热衷.1 天前
YOLO26-Seg ONNXruntime C++/python推理
开发语言·c++·python
YMWM_1 天前
如何将包路径添加到conda环境lerobot的python路径中呢?
人工智能·python·conda
靓仔建1 天前
Vue3导入组件出错does not provide an export named ‘user_setting‘ (at index.vue:180:10)
开发语言·前端·typescript
田里的水稻1 天前
ubuntu22.04_openclaw_ROS2
人工智能·python·机器人
梁正雄1 天前
Python前端-2-css练习
前端·css·python
wefly20171 天前
开发者效率神器!jsontop.cn一站式工具集,覆盖开发全流程高频需求
前端·后端·python·django·flask·前端开发工具·后端开发工具
赶路人儿1 天前
UTC时间和时间戳介绍
java·开发语言
6+h1 天前
【java】基本数据类型与包装类:拆箱装箱机制
java·开发语言·python
GDAL1 天前
MANIFEST.in简介
linux·服务器·前端·python
MoRanzhi12031 天前
pillow 图像合成、透明叠加与蒙版处理
python·计算机视觉·pillow·图片处理·图像合成·透明叠加·多图层叠加