考虑以下扩展list
的类并附加orderedtuple
s:
from collections import namedtuple
Order = namedtuple('Order', ['id', 'value'])
class Orders(list):
def __init__(self, *args):
super(Orders, self).__init__()
self.extend(args)
def add(self, id, value):
self.append(Order(id, value))
...添加一些元素......
order = Orders()
order.add(1, 'alpha')
order.add(2, 'beta')
order.add(3, 'lambda')
order.add(4, 'omega')
......我们离开......
print order
[Order(id=1, value='alpha'), Order(id=2, value='beta'), Order(id=3, value='lambda'), Order(id=4, value='omega')]
说我想删除id
的任意元素。例如:
order.remove(id=2) # ideal function call to remove by `id`
print order
[Order(id=1, value='alpha'), Order(id=3, value='lambda'), Order(id=4, value='omega')]
是否有一种相当简单的方法可以实现这一目标?
答案 0 :(得分:3)
你可以慢慢地这样做:
def remove(self, id=None, value=None):
for elem in self:
if (id is not None and elem.id == id or
value is not None and elem.value == value):
super(Orders, self).remove(elem)
break
您可以向类中添加一个索引,用于跟踪地图ID和/或值到特定索引,但在操作包含的订单列表时,您需要使该索引保持最新。它看起来像这样:
def __init__(self, *args):
# ...
self._ids = {}
def append(self, id, value):
if id in ids:
raise ValueError('This order already exists!')
super(Orders, self).append(Order(id, value))
self._ids[id] = len(self) - 1
并且,如果您还调整了可以更改列表和更改排序等的所有其他方法,您可以通过其ID快速查找订单:
def remove(self, id):
if id not in self._ids
raise ValueError('No such order exists!')
del self[self._ids[id]]
答案 1 :(得分:3)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform_1">
<select class="form-control" name="tipo">
<option value="standard">standard</option>
</select>
<input type="number" name="giorni" value="90"/>
<input type="number" name="attesa" value="1"/>
<button type="button" onclick="FormManipulator(this)">Crea</button>
</form>
<form id="myform_2">
<select class="form-control" name="tipo">
<option value="standard">standard</option>
</select>
<input type="number" name="giorni" value="90"/>
<input type="number" name="attesa" value="1"/>
<button type="button" onclick="FormManipulator(this)">Crea</button>
</form>
答案 2 :(得分:1)