for循环中的多列表重复消除

2024-06-16 14:47:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,必须同时检查两个列表中的重复项。对于笛卡尔坐标系,一个列表有x值,另一个列表有y值。一个坐标不能重复。当前我的代码如下所示:

    for q in range(0, len(prows)-1, 1):
            for w in range(0, len(prows)-1, 1):
                if prows[q] == prows[w] and pcols[q] == prows[w]:
                    prows.remove(prows[w])
                    pcols.remove(pcols[w])

其中prows是y值,pcols是x值。这是可行的,问题是我的第一个for循环只在第二个for循环遍历它的所有值之后更新船头的长度。由于这个原因,我得到了一个索引错误,第一个for循环仍然具有原始的长度prows,而第二个for循环具有删除了重复项的较新长度。你知道吗


Tags: and函数代码in列表forlenif
2条回答

使用dict保留其键的插入顺序(在Python 3.7中是will become part of the specification,但在3.6中已经是这样)这一事实,可以在一个简短的行中完成:

# create some data       
>>> import random
>>> a = [random.randint(0, 3) for _ in range(20)]
>>> b = [random.randint(0, 3) for _ in range(20)]
>>> 
>>> a
[0, 3, 2, 1, 2, 0, 1, 2, 0, 2, 1, 1, 0, 3, 1, 3, 1, 2, 3, 2]
>>> b
[1, 0, 3, 2, 2, 2, 2, 3, 1, 2, 1, 1, 1, 1, 3, 0, 0, 0, 3, 3]
>>> 
# this one line is all we need
>>> au, bu = zip(*dict.fromkeys(zip(a, b)))
>>> 
# admire
>>> au
(0, 3, 2, 1, 2, 0, 1, 3, 1, 1, 2, 3)
>>> bu
(1, 0, 3, 2, 2, 2, 1, 1, 3, 0, 0, 3)

请注意,与人们可能期望的相反,这对集合不起作用-实际上必须使用dict(带有伪值)。你知道吗

xlist = [ 1, 3, 5, 7, 9, 5]
ylist = [11,33,55,77,99,55]   # (5,55) dupe'd

coords = list(zip(xlist,ylist)) # list of unique coords

print(coords) # still has dupes

result = []       # empty result list, no dupes allowed
setCoords = set() # remember which coords we already put into result
for c in coords:  # go through original coords, one at a time
    if c in setCoords:  # we already added this, skip it
        continue
    setCoords.add(c)    # add to set for comparison
    result.append(c)    # add to result

print(result) # no dupes, still in order of list

输出:

[(1, 11), (3, 33), (5, 55), (7, 77), (9, 99), (5, 55)] # coords, with dupes
[(1, 11), (3, 33), (5, 55), (7, 77), (9, 99)]          # result, no dupes

也可以通过执行以下操作恢复到xlist和ylist:

x2 , y2 = [list(tups) for tups in zip(*result)]

print(x2)
print(y2)

输出:

[1, 3, 5, 7, 9] 
[11, 33, 55, 77, 99]

相关问题 更多 >