比较3个列表并删除所有匹配的元素

2024-09-28 17:03:24 发布

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

我想比较3个列表,每当出现匹配时,列表中的元素都会被删除。你知道吗

(->;每次gpos=G00、xpos=0和ypos=0)

gpos = ['G01','G01','G00','G00','G00','G00','G00','G00','G00','G00']
xpos = ['249','248', '0' , '0' , '72', '0' , '66','67' ,'81' , '82']
ypos = ['18', '28' , '0' , '0' , '52', '0',  '53','55' ,'54' , '52']

---------------------
the output should be:
---------------------

gpos = ['G01','G01','G00',G00','G00','G00','G00']
xpos = ['249','248', '72','66','67' ,'81' , '82']
ypos = ['18', '28' , '52','53','55' ,'54' , '52']

我不知道该怎么办


Tags: thegt元素列表outputbeshouldxpos
3条回答

这是相当粗糙的,但它会工作。你知道吗

for index,element in enumerate(xpos):
 if element == '0':
  if ypos[index] == '0':
   if gpos[index] == 'G00':
    del gpos[index]
    del xpos[index]
    del ypos[index]

更重要的是,你至少应该试过一些东西,把它和问题放在一起。不管你错了多少,但你应该尽最大努力自己编写代码。你知道吗

您可以使用来自itertoolsizip,并同时迭代您的3个列表。你知道吗

然后,当xposypos等于'0'时,删除元组。你知道吗

new_gpos = list()
new_xpos = list()
new_ypos = list()

for (a,b,c) in itertools.izip(gpos, xpos, ypos):
    if not (b == c == '0'):
        print a, b, c
        new_gpos.append(a)
        new_xpos.append(b)
        new_ypos.append(c)
# Input data
gpos = ['G01','G01','G00','G00','G00','G00','G00','G00','G00','G00']
xpos = ['249','248', '0' , '0' , '72', '0' , '66','67' ,'81' , '82']
ypos = ['18', '28' , '0' , '0' , '52', '0',  '53','55' ,'54' , '52']

# Input match (as a tuple)
match = ('G00', '0', '0') 

您可以前后转置它们(考虑列而不是行)并进行筛选。你知道吗

# Flipper
transpose = lambda x: [list(col) for col in zip(*x)]

# Filter input
gpos, xpos, ypos = transpose([col for col in zip(gpos, xpos, ypos) if col != match])

print gpos # ['G01', 'G01', 'G00', 'G00', 'G00', 'G00', 'G00']
print xpos # ['249', '248', '72',  '66',  '67',  '81',  '82']
print ypos # ['18',  '28',  '52',  '53',  '55',  '54',  '52']

备选方案一班轮(由Blckknght建议):

gpos, xpos, ypos = map(list, zip(*[gxy for gxy in zip(gpos, xpos, ypos) if gxy != match]))

相关问题 更多 >