0

我有一个清单。

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

我想使用列表理解并希望将输出创建为:

output1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]

output2:
('value', 1)
('value', 2)
'
'
('value', 20)

我可以使用 for 循环创建 output1 和 output2,但我不知道如何使用列表理解。

如果有人知道这一点,请告诉我。

提前致谢。

4

3 回答 3

8

For the First you can do something like

>>> [a[i:i+4] for i in range(0,len(a),4)]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]

For the Second you can simply read and generate the tuples with value as the first item

>>> [('value',i) for i in a]
[('value', 1), ('value', 2), ('value', 3), ('value', 4), ('value', 5), ('value', 6), ('value', 7), ('value', 8), ('value', 9), ('value', 10), ('value', 11), ('value', 12), ('value', 13), ('value', 14), ('value', 15), ('value', 16), ('value', 17), ('value', 18), ('value', 19), ('value', 20)]

another version using itertools.izip_longest though the above is more redable

list(itertools.izip_longest([],a,fillvalue='value'))
于 2012-04-18T13:11:12.897 回答
4
output1 = [a[i:i+4] for i in xrange(0,len(a),4)]
output2 = [('value',i) for i in a]
于 2012-04-18T13:11:11.133 回答
4

这是JF Sebastians 的 grouper,它解决了您的第一个问题:

 from itertools import izip_longest, repeat
 izip_longest(*[iter(a)]*4, fillvalue=None)

对于你的第二个:zip(repeat('value'), a)

于 2012-04-18T13:14:48.570 回答