Python子列表创建

时间:2013-01-11 17:20:38

标签: python sublist

我有一个洗牌的列表,然后我希望它被分解为6个子元素,每个子元素包含6个元素(原始列表中有26个元素)。我知道需要通过范围(例如0-5,6-11等)创建子列表来完成,但无法找到方法。应该很直接!到目前为止,这是我的代码:

import random

characters = [0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

random.shuffle(characters)

3 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

>>> import string
>>> import random
>>>
>>> chars = list(string.uppercase + string.digits)
>>> random.shuffle(chars)
>>>
>>> [chars[i:i + 6] for i in range(0, len(chars), 6)]
[['U', 'I', 'X', '6', 'Q', 'L'],
 ['Y', 'J', 'C', 'S', '8', '0'],
 ['A', 'R', '5', 'F', 'T', 'W'],
 ['N', 'B', 'E', '2', '1', 'V'],
 ['9', 'K', 'O', 'P', '7', '4'],
 ['G', 'M', 'Z', '3', 'D', 'H']]
  • chars[i:i + 6]创建一个长度为6的子列表,从i位置开始。
  • range(0, len(chars), 6)0为增量在len(chars)6范围内循环:

    >>> range(0, len(chars), 6)
    [0, 6, 12, 18, 24, 30]
    

答案 1 :(得分:1)

使用itertools.islice()

In [246]: characters = [0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

In [247]: it=iter(characters)

In [248]: [list(islice(it,6)) for _ in range(6)]
Out[248]: 
[[0, 1, 2, 3, 4, 5],
 [6, 7, 8, 9, 'A', 'B'],
 ['C', 'D', 'E', 'F', 'G', 'H'],
 ['I', 'J', 'K', 'L', 'M', 'N'],
 ['O', 'P', 'Q', 'R', 'S', 'T'],
 ['U', 'V', 'W', 'X', 'Y', 'Z']]

iter(characters):创建一个characters列表的迭代器。

islice(iterator,len):返回len=6的迭代器片段。 Islice对象本身就是一个迭代器,因此,您需要将islice对象传递给list()才能获取它的内容。

传递给6的{​​{1}}可以通过以下方式获取:

range

答案 2 :(得分:1)

基于itertools石斑鱼配方

依赖itertools.izip_longest和自增量或迭代器

>>> list(izip_longest(*[iter(characters)] * 6))
[(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 'A', 'B'), ('C', 'D', 'E', 'F', 'G', 'H'), ('I', 'J', 'K', 'L', 'M', 'N'), ('O', 'P', 'Q', 'R', 'S', 'T'), ('U', 'V', 'W', 'X', 'Y', 'Z')]