问题描述
我是Python的初学者,我必须在两个列表之间进行XOR(第一个列表的长度为600,另一个为60)
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.
我必须这样做才能找到BPSK信号模块,我想知道如何使用两个长度不相同的列表来做到这一点.我看到了这篇文章:比较两个列表且仅印刷差异? (将两个列表异或),但是列表的长度相同
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 englishRom
推荐答案
给出序列seq1
和seq2
,您可以计算对称差异与
Given sequences seq1
and seq2
, you can calculate the symmetric difference with
set(seq1).symmetric_difference(seq2)
例如,
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
之所以可能要使用symmetric difference
而不是^
(尽管其语法优美)是因为symmetric difference
方法可以将列表作为输入. ^
要求同时设置两个输入.将两个列表都转换为集合比最小需要的计算量要多.
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 questionThat question, however, is seeking a solution to this problem without using sets.
可接受的解决方案,
[a for a in list1+list2 if (a not in list1) or (a not in list2)]
如果允许使用集合,则不建议使用
对两个列表进行异或.一方面,它的速度要慢100倍以上:
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
这篇关于在Python中的两个列表上进行异或的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!