python中异或怎么算_在Python中的两个列表上进行异或

I'm a beginner in Python, and I have to do the XOR between two lists (the first one with the length : 600 and the other 60)

I really don't know how to do that, if somebody can explain me how, it will be a pleasure.

I have to do that to find the BPSK signal module, and I'm wondering on how doing that with two lists that haven't the same length. I saw this post : Comparing two lists and only printing the differences? (XORing two lists) but the length of lists is the same

Thanks for your help, and sry for my bad english

Rom

解决方案

Given sequences seq1 and seq2, you can calculate the symmetric difference with

set(seq1).symmetric_difference(seq2)

For example,

In [19]: set([1,2,5]).symmetric_difference([1,2,9,4,8,9])

Out[19]: {4, 5, 8, 9}

Tip: Generating the set with the smaller list is generally faster:

In [29]: %timeit set(range(60)).symmetric_difference(range(600))

10000 loops, best of 3: 25.7 µs per loop

In [30]: %timeit set(range(600)).symmetric_difference(range(60))

10000 loops, best of 3: 41.5 µs per loop

The reason why you may want to use symmetric difference instead of ^ (despite the beauty of its syntax) is because the symmetric difference method can take a list as input. ^ requires both inputs be sets. Converting both lists into sets is a little more computation than is minimally required.

This question has been marked of as a duplicate of this question

That question, however, is seeking a solution to this problem without using sets.

The accepted solution,

[a for a in list1+list2 if (a not in list1) or (a not in list2)]

is not the recommended way to XOR two lists if sets are allowed. For one thing, it's over 100 times slower:

In [93]: list1, list2 = range(600), range(60)

In [94]: %timeit [a for a in list1+list2 if (a not in list1) or (a not in list2)]

100 loops, best of 3: 3.35 ms per loop

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值