【发布时间】:2011-02-15 04:46:17
【问题描述】:
我有 n 个元组列表 (n
Example Input:
[('A',[(0.12, 'how'),(0.26,'are'),(0.7, 'you'),(0.9,'mike'),(1.9, "I'm fine too")]),
('B',[(1.23, 'fine'),(1.50, 'thanks'),(1.6,'and you')]),
('C',[(2.12,'good'),(2.24,'morning'),(3.13,'guys')])]
Desired Output:
[('A', ( 0.12, 'how')),
('A', ( 0.26, 'are')),
('A', ( 0.7, 'you')),
('A', ( 0.9, 'mike')),
('B',(1.23, 'fine')),
('B',(1.50, 'thanks')),
('B',(1.6,'and you')),
('A', (1.9, "I'm fine too")),
('C',(2.12,'good')),
('C',(2.24,'morning')),
('C',(3.13,'guys'))]
我知道代码很难看,尤其是那些索引 item[0][-1][1],但是有人能告诉我我做错了什么吗?
content = []
max = 0.0
first = True
Done = False
finished = []
while not Done:
for item in flow:
if len(finished) == 4:
Done = True
break
if len(item[1]) == 0:
if item[0] not in finished:
finished.append(item[0])
continue
if first == True:
max = item[1][-1][0]
content.append((item[0], item[1].pop()))
first = False
continue
if item[1][-1][0] > max:
max = item[1][-1][0]
content.append((item[0], item[1].pop()))
content = sorted(content, key=itemgetter(1))
first = True
更新: 谢谢大家
【问题讨论】:
-
Timsort 对于部分排序的数据非常快。你的工作量太大了。
-
不要使用max作为变量名,你可能希望有一天能够使用内置函数
max() -
听起来你想做的很简单,但你给我们的只是一些令人困惑的输出,甚至不是python结构,也没有示例输入。例如,在您的输出中,列表 ID 都分组在一起。请提供一些有效的 python 数据结构来显示输入和所需的输出
标签: python algorithm sorting tuples merge