我有一个对象列表。每个对象都是一个唯一的实例,由名称和值的任意组合组成。我想将具有重复名称的对象组合到同一类的新实例中,其值是所有重复项的值的列表。这是我非常非pythonic的方法:
def normalise_repeatable_options(options):
flat = {}
for o in options:
if isinstance(o, Option):
flat.setdefault(o.long, []).append(o)
# Ensure options stay in the order they were prescribed.
parsed = []
for o in options:
if isinstance(o, Option):
dups = flat.get(o.long)
if dups:
parsed.append(Option.combine(*tuple(dups)))
del flat[o.long]
else:
parsed.append(o)
return parsed
更新:函数的输入和预期输出
input = [
Option('-f', '--filter', 1, 'merge file'),
Option('-f', '--filter', 1, 'merge anotherfile'),
Argument(None, 'a'),
Argument(None, 'b'),
Argument(None, 'c')
]
output = [
Option('-f', '--filter', 1, ['merge file', 'merge anotherfile']),
Argument(None, 'a'),
Argument(None, 'b'),
Argument(None, 'c')
]
我还包括了Object.combine
类方法,以防你想知道它的作用:
@classmethod
def combine(class_, *opts):
t = opts[0]
if len(opts) == 1: return t
return class_(t.short, t.long, t.argcount, [o.value for o in opts])