mat*_*eek 0 python sorting algorithm merge tuples
我有n个列表(n <10)的格式[(ListID,[(索引,值),(索引,值),...)]并希望按索引对它们进行排序以获得以下结果
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'))]
Run Code Online (Sandbox Code Playgroud)
我知道代码是丑陋的,特别是那些索引项[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
Run Code Online (Sandbox Code Playgroud)
更新:谢谢大家
>>> from operator import itemgetter
>>> import pprint
>>> pprint.pprint(sorted(((i,k) for i,j in INPUT for k in j), key=itemgetter(1)))
[('A', (0.12, 'how')),
('A', (0.26000000000000001, 'are')),
('A', (0.69999999999999996, 'you')),
('A', (0.90000000000000002, 'mike')),
('B', (1.23, 'fine')),
('B', (1.5, 'thanks')),
('B', (1.6000000000000001, 'and you')),
('A', (1.8999999999999999, "I'm fine")),
('C', (2.1200000000000001, 'good')),
('C', (2.2400000000000002, 'morning')),
('C', (3.1299999999999999, 'guys'))]
Run Code Online (Sandbox Code Playgroud)
这里有两个主要的事情
[(i,k) for i,j in INPUT for k in j]
Run Code Online (Sandbox Code Playgroud)
将INPUT转换为此结构
[('A', (0.12, 'how')),
('A', (0.26, 'are')),
('A', (0.7, 'you')),
('A', (0.9, 'mike')),
('A', (1.9, "I'm fine")),
('B', (1.23, 'fine')),
('B', (1.5, 'thanks')),
('B', (1.6, 'and you')),
('C', (2.12, 'good')),
('C', (2.24, 'morning')),
('C', (3.13, 'guys'))]
Run Code Online (Sandbox Code Playgroud)
和
sorted(L, key=itemgetter(1))
Run Code Online (Sandbox Code Playgroud)
分类L购买每个元素的项目[1].这实际上是(0.12,'how'),(0.27,'是')...但是python对元组排序的正常方式是从左到右,所以我们不需要做额外的工作来从中删除单词元组
归档时间: |
|
查看次数: |
1641 次 |
最近记录: |