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

时间:2014-06-26 14:42:51

标签: python python-3.x

HY,

我想比较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']

我不知道该做什么O_o

3 个答案:

答案 0 :(得分:1)

您可以使用izip中的itertools,并同时在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)

答案 1 :(得分:1)

# 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]))

答案 2 :(得分:-1)

这相当粗糙,但它会起作用。

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]

只是为了补充一点,你应该至少尝试过一些东西并把它与问题放在一起。你有多么不对,但你应该尽量自己编码。