<p>下面是我们的uniques函数。它接受参数l(list)和f(function),返回去掉重复项的list(以相同的顺序)。重复定义为:b是iff(b)==f(a)的重复。在</p>
<pre><code>def uniques(l, f = lambda x: x):
return [x for i, x in enumerate(l) if f(x) not in [f(y) for y in l[:i]]]
</code></pre>
<p>最后两个定义如下:</p>
^{pr2}$
<p>对于您的问题,我们使用如下方法:</p>
<pre><code>>>> list1
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
>>> list2
[('b', 'b', 'c'), ('d', 'e', 'a'), ('k', 'h', 'i')]
>>> uniques(list1+list2, lastTwo)
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('d', 'e', 'a')]
</code></pre>
<p>如果你描述的用例出现了很多你可能想要定义的</p>
<pre><code>def hervesMerge(l1, l2):
return uniques(l1+l2, lambda x: x[-2:])
</code></pre>
<p>Identity是我们的默认f,但它可以是任何东西(只要它是为列表的所有元素定义的,因为它们可以是任何类型的)。在</p>
<p>f可以是列表的和,列表的奇数元素,整数的素数因子,任何东西。(只要记住,如果它是内射的就没有意义了!按常数相加,线性函数等的作用与恒等式相同,它的f(x)==f(y)w/x!=有区别的y)</p>
<pre><code>>>> list1
[(1, 2, 3, 4), (2, 5), (6, 2, 2), (3, 4), (8, 3), (1, 1, 1, 1, 1, 1, 1, 1, 1, 1)]
>>> uniques(list1, sum)
[(1, 2, 3, 4), (2, 5), (8, 3)]
>>> uniques(list1, lambda x: reduce(operator.mul, x)) #product
[(1, 2, 3, 4), (2, 5), (3, 4), (1, 1, 1, 1, 1, 1, 1, 1, 1, 1)]
>>> uniques([1,2,3,4,1,2]) #defaults to identity
[1, 2, 3, 4]
</code></pre>
<p>我的回答很有弹性吗提高速度。对于速度与z有关的更大的列表,您希望利用散列检查和已知的list1和list2没有重复项这一事实</p>
<pre><code>>>> s = frozenset(i[-2:] for i in list1)
>>> ans = list(list1) #copy list1
>>> for i in list2:
if i[-2:] not in s: ans.append(i)
>>> ans
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('d', 'e', 'a')]
</code></pre>
<p>或者允许混乱</p>
<pre><code>>>> d = dict()
>>> for i in list2 + list1:
d[i[-2:]] = i
>>> d.values()
[('d', 'e', 'f'), ('a', 'b', 'c'), ('g', 'h', 'i'), ('d', 'e', 'a')]
</code></pre>
<p>编辑</p>
<p>你应该总是能够避免非Python式的循环,就像你在你的问题中所说的那样。以下是更改循环后的确切代码:</p>
<pre><code>for k in temp:
u=0
for j in result:
if k[1:3] == j[1:3]:
u=1
break
if u==0:
#if index is None:
result.append([k[0],k[1],k[2]]) // k
</code></pre>
<p>result和temp是iterable,对于iterable的任何东西,您可以直接将其放入for循环中,而无需使用eanges。如果出于某种原因您显式需要索引(这不是这种情况,但是我上面有一个),您可以使用enumerate。在</p>