python - 如何合并 0 或 1 的字符串,就好像我在 python 中的位域上做 OR 一样?
问题描述
例如,对于字符串“000100”、“010000”和“100000”,我希望结果为“110100”。
Python中有一个简单的方法吗?
解决方案
You can convert each binary string to their actual integer value by using int(<str>, 2)
, then use the binary or operation (|
) to merge them together and get the binary representation back by using bin
:
>>> binstrings = ['000100', '010000', '100000']
>>> result = 0
>>> for s in binstrings:
... result |= int(s, 2)
...
>>> result
52
>>> bin(result)
'0b110100'
推荐阅读
- apache - 使用 Httpd 代理运行 Portainer 时 Websocket 无法正常工作
- xml - AWS S3 存储桶 cors 配置错误 - 您提供的 XML 格式不正确或未针对我们发布的架构进行验证
- node.js - 最近通过 Digitalocean 负载平衡器连接 socket.io 时遇到问题(400 错误)
- java - 是什么导致此 Graphics2D 渲染卡顿/滞后
- yarnpkg - 如何更改我的 Yarn Workspace 包的名称?
- c# - 使用 sqlbulktools 更新表时对列值求和
- javascript - 如何在 jquery ui 选择输入中设置日期
- excel - 根据唯一 ID 从源工作表中获取目标工作表中的值
- rust - 以编程方式在 Rust 上创建字符串切片
- node.js - MSSQL Nodejs Streaming 不等待完成返回