Segment = namedtuple('Segment', 'start end')
segments = [Segment(start=9, end=1), Segment(start=1, end=3), Segment(start=2, end=5), Segment(start=3, end=6)]
我尝试使用以下代码对列表进行排序:
sorted(segments, key = lambda s: s.end - s.start)
但这不起作用。我怎么能这样做?
预期产出:
[Segment(start=3, end=6), Segment(start=2, end=5), Segment(start=1, end=3), Segment(start=9, end=1)]
答案 0 :(得分:2)
您需要指定您想要&#34;序列&#34;首先是end - start < 0
或segments
,如果有许多end
符合该条件,则应优先考虑&#34; sequence&#34;最高>>> from collections import namedtuple
>>> Segment = namedtuple('Segment', 'start end')
>>> segments = [Segment(start=9, end=1), Segment(start=1, end=3), Segment(start=2, end=5), Segment(start=3, end=6)]
>>> sorted(segments, key=lambda s: (s.end < s.start, -s.end))
[Segment(start=3, end=6), Segment(start=2, end=5), Segment(start=1, end=3), Segment(start=9, end=1)]
值。
<div id="header"></div>
<div id="content">
<div class="sidebar-wrapper"></div>
</div>
<div class="session-wrapper"></div>
<div id="footer"></div>