当元组通过时,从列表中删除所有类似的对象。如果元组失败,请尝试下一个

时间:2019-02-16 19:10:03

标签: python list tuples iteration

我感觉除了脚垫和车把,我已经拥有了这辆自行车的所有部件。以我对这种语言的理解,我还没有 “座椅”和“车把”的名称,而不是“旋转手的东西”和“我们必须站立才能骑这东西吗?”

我有一个列表,其中包含ID,目标和标签的元组。 ID和目标已配对并用于作业队列,这可能导致通过或失败。

如果ID过去了,我希望将包含该ID的所有其他元组从列表中删除,从而允许刷新后的列表继续迭代。如果ID失败,我只希望从列表中删除该尝试的ID及其元组元素-从而有机会使相同的ID(包含该ID的元组)尝试另一个目标。

下面,我已经发布了期望的结果,许多编码尝试之一以及与此问题相关的其他一些StackOverflow帖子。我的编码 尝试可能是对问题的错误尝试。我对列表理解的理解是有限的,但是我觉得这可能对您有用。我有 也考虑使用字典。

相关问题:

编码尝试

s,m,l = ("s","m","l")

list = [(11, '853', s), (12, '853', s), (13, '853', m),
 (11, '421', l), (12, '421', l), (13, '421', s)]

passlist=[]
faillist=[]

jobfail = 13
jobpass = 11

def process(list):
 for e in list:
  if jobfail in e:
   print("jobfail:", e)
   faillist.append(e)
   list.pop()
   continue
  if jobpass in e:
   print("jobpass:", e)
   passlist.append(e)
   list.pop()
  print("list is now:", list)
 return passlist,faillist

print("original list:", list)
process(list)
print("passlist:", passlist)
print("faillist:", faillist)
print("final list:", list)

所需结果

('original list:', [(11, 853, 's'), (12, 853, 's'), (13, 853, 'm'), (11, 421, 'large'), (12, 421, 'large'), (13, 421, 's')])

Processing 11 -> 853
('jobpass:', (11, 853, 's'))
('passlist:', [(11, 853, 's')])
('faillist:', [])
Any tuple with id = 11 is removed:
('list is now:', [(12, 853, 's'), (13, 853, 'm'), (12, 421, 'large'), (13, 421, 's')])

Processing 12 -> 853
('jobpass:', (12, 853, 's'))
('passlist:', [(11, 853, 's'), (12, 853, 's')])
('faillist:', [])
Any tuple with id = 12 is removed:
('list is now:', [(13, 853, 'm'), (13, 421, 's')])

Processing 13 -> 853
('jobfail:', (13, 853, 'm'))
('passlist:', [(11, 853, 's'), (12, 853, 's')])
('faillist:', [(13, 853, 'm')])
We had a failure, so let's try the next pairing:
('list is now:', [(13, 421, 's')])

Processing 13 -> 421
('jobpass:', (13, 421, 's'))
('passlist:', [(11, 853, 's'), (12, 853, 's'), (13, 421, 's')])
('faillist:', [(13, 853, 'm')])
('list is now:', [])

0 个答案:

没有答案