Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 负边界切片_Python_Tuples_Slice_Negative Number - Fatal编程技术网

Python 负边界切片

Python 负边界切片,python,tuples,slice,negative-number,Python,Tuples,Slice,Negative Number,我有两个n长度的元组,我需要检查除了位置w的元素外,是否所有位于相同位置的元素都相同。这是我写的: if all(tup1[i] == tup2[i] for i in xrange(n) if i != w): ... 为了避免循环(因为这段代码将被多次使用),我尝试使用切片。不幸的是,这不起作用: if tup1[w-1:w-n:-1] == tup2[w-1:w-n:-1]: ... 我必须写这样的东西吗 if tup1[:w-1] == tup2[:w-1] and

我有两个n长度的元组,我需要检查除了位置w的元素外,是否所有位于相同位置的元素都相同。这是我写的:

if all(tup1[i] == tup2[i] for i in xrange(n) if i != w):
    ...
为了避免循环(因为这段代码将被多次使用),我尝试使用切片。不幸的是,这不起作用:

if tup1[w-1:w-n:-1] == tup2[w-1:w-n:-1]:
    ...
我必须写这样的东西吗

if tup1[:w-1] == tup2[:w-1] and tup1[w+1:] == tup2[w+1:]
难道没有更优雅的方法吗


或者循环和切片都不好,有更好的方法获得我想要的结果吗?(我无法使用过滤器,因为可能存在与位置w中的元素值相同的元素)

我认为您已经找到了最佳解决方案:

 tup1[:w-1] == tup2[:w-1] and tup1[w+1:] == tup2[w+1:]
如果元组非常长,并且您不想复制数据,并且希望提前退出,那么使用itertools和operator有一种更复杂的替代方法:

这是一个大量的设置工作,逐步的速度不如元组切片,但它确实避免了复制所有的数据,而且它有一个早期的输出


在非极端情况下,我会坚持使用双切片元组相等解决方案。

all
方法会更好,因为切片元组时,将通过迭代创建原始元组的副本。但是当您使用
all
时,如果两个元素不同,元组的其余部分将根本不会被迭代。这肯定是过早优化的情况。您试图迭代n-1项(可忽略的优化),每次都要复制整个列表!在分析告诉您有问题之前不要进行优化。事实上,这里甚至没有嵌套循环。均衡两个iterables和执行for循环检查所需的复杂性都是线性的。因此,无需进行优化。
>>> from operator import eq
>>> from itertools import imap
>>> w = 5
>>> t1 = (10, 20, 30, 40, -1, 50, 60, 70)
>>> t2 = (10, 20, 30, 40, -1, 50, 60, 70)
>>> it1, it2 = iter(t1), iter(t2)
>>> all(imap(eq, islice(it1, w-1), islice(it2, w-1))) \
    and (next(it1, True) or True) and (next(it2, True) and True) \
    and all(imap(eq, it1, it2))
True