You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中对二进制字符串异或结果的每一位再做XOR运算的实现方法

解决二进制字符串逐位连续XOR的问题

你已经完成了两个二进制字符串的XOR运算得到result列表,接下来要对每一位做连续XOR,可以用两种简洁的方法实现:

方法1:逐位遍历异或

初始化一个初始值为0的变量,遍历result中的每一位,将字符转为整数后和当前变量做异或操作,最后把结果转回字符串:

a = "0101"
b = "0010"
result = []
for x, y in zip(a, b):
    if x == y:
        result.append('0')
    else:
        result.append('1')

# 执行连续异或操作
current_xor = 0
for bit in result:
    current_xor ^= int(bit)
final_result = str(current_xor)

print(final_result)  # 输出:1

方法2:统计1的个数奇偶性

根据异或运算的特性:偶数个1连续异或结果为0,奇数个1连续异或结果为1。所以直接统计result中'1'的个数,判断奇偶性即可得到结果:

a = "0101"
b = "0010"
result = []
for x, y in zip(a, b):
    if x == y:
        result.append('0')
    else:
        result.append('1')

# 统计1的个数并判断奇偶
count_ones = result.count('1')
final_result = '1' if count_ones % 2 == 1 else '0'

print(final_result)  # 输出:1

两种方法最终都会得到0^1^1^1的结果1,你可以根据需求选择其中一种。

内容的提问来源于stack exchange,提问作者efe373

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 12:13:53