基于字符串整数作为索引创建元组元素的嵌套列表

时间:2016-06-20 11:18:16

标签: python tuples sublist

假设我有一个包含列表的元组,其第一个元素总是一个字符串数字,例如。

3.0, 3.1, 3.2 and 5.0, 5.1

Baiscally,我希望有一个列表,其中包含元组列表的所有字符串数。

但是,如果每个列表的第一个值包含子索引(在本例中为Result = ['0', '1', '2', ['3.0', '3.1', '3.2'], '4', ['5.0', '5.1']] ),我想将这些子值放在一个子列表中。此示例中的结果应如下所示。

I hope this is helped to u

  NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"Enter Name (minimum 6 char)"];
[hogan addAttribute:NSFontAttributeName
              value:[UIFont systemFontOfSize:12.0]
              range:NSMakeRange(11, 16)];


NSRange rangeOfUsername = [[hogan string] rangeOfString:@"Enter Name"];
if (rangeOfUsername.location != NSNotFound) {
    [hogan addAttribute:NSForegroundColorAttributeName
                  value:[UIColor redColor]
                  range:rangeOfUsername];
}


textX.attributedPlaceholder = hogan;

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

使用itertools.groupby

import operator
import itertools

tuples = (['0', ], ['1', ], ['2', ], ['3.0', ], ['3.1', ], ['3.2', ], ['4', ] , ['5.0', ], ['5.1', ])

l = map(operator.itemgetter(0), tuples)
# ['0', '1', '2', '3.0', '3.1', '3.2', '4', '5.0', '5.1']

results = list()
for name, group in itertools.groupby(l, key=lambda x:x.split('.')[0]):
    tmp_list = list(group)
    results.append(tmp_list[0] if len(tmp_list)==1 else tmp_list)

print(results)
# Output
['0', '1', '2', ['3.0', '3.1', '3.2'], '4', ['5.0', '5.1']]

答案 1 :(得分:0)

您也可以不使用itertools.groupby()来执行此操作。你可以使用像这样的排序方法/ defaultdict方法:

from collections import defaultdict

asdf = (['0', ], ['1', ], ['2', ], ['3.0', ], ['3.1', ], ['3.2', ], ['4', ] , ['5.0', ], ['5.1', ])

all_items = [x[0] for x in asdf]

d = defaultdict(list)

for item in all_items:
    key = item[0]
    d[key].append(item)

values = [x[1] for x in sorted(d.items())]

result = []
for lst in values:
    if len(lst) == 1:
        result.append(lst[0])
    else:
        result.append(lst)
print(result)

输出:

['0', '1', '2', ['3.0', '3.1', '3.2'], '4', ['5.0', '5.1']]

这也可以没有默认条件。

相关问题