-1

我有一个以这种方式列出的列表。

[['Introduction', '0 11 0 1 0'],
['Floating', '0 11 33 1 0'],
['point', '0 11 33 1 1'],
['numbers', '0 11 33 1 2'],
['IEEE', '0 11 58 1 0'],
['Standard', '0 11 58 1 1'], 
['754', '0 11 58 1 2']]

我想根据其字符串索引对列表中的单词进行聚类/分组。分组基于字符串索引的前 3 个数字。解决这个问题的最佳方法是什么。我正在考虑使用正则表达式。这个分组有直接简单的方法吗?

预期输出:

Introduction 0 11 0
Floating point numbers 0 11 33
IEEE Standard 754  0 11 58
4

1 回答 1

5

也许使用itertools.groupby

from itertools import groupby
def key(item):
    return [int(x) for x in item[1].split()[:3]]

master_lst = [['Introduction', '0 11 0 1 0'],
              ['Floating', '0 11 33 1 0'],
              ['point', '0 11 33 1 1'],
              ['numbers', '0 11 33 1 2'],
              ['IEEE', '0 11 58 1 0'],
              ['Standard', '0 11 58 1 1'], 
              ['754', '0 11 58 1 2']]

for k,v in groupby(master_lst,key=key):
    print ' '.join(x[0] for x in v) +' ' + ' '.join(str(x) for x in k)

结果是:

Introduction 0 11 0
Floating point numbers 0 11 33
IEEE Standard 754 0 11 58
于 2013-04-15T16:13:58.573 回答