1

我有一个被打乱的列表,然后我希望它被分解为 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)
4

3 回答 3

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')]
于 2013-01-11T17:25:16.710 回答
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创建一个从 position 开始的长度子列表i
  • range(0, len(chars), 6)0在范围 from到 以len(chars)为增量循环6

    >>> range(0, len(chars), 6)
    [0, 6, 12, 18, 24, 30]
    
于 2013-01-11T17:23:27.817 回答
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传递给range可以通过以下方式获得:

In [2]: int(len(characters)/6)
Out[2]: 6
于 2013-01-11T17:23:29.493 回答