Python:将列表拆分为集合
Python: Split list in to sets
我正在尝试将列表拆分为枚举集,我有一个实现似乎可以满足我的要求,但感觉不是很“pythonic”有没有更好的方法?
下面的示例将项目拆分为最大大小为 3 的集合,returns 项目中的每个项目以及集合编号和集合索引
items = [1,2,3,4,5,6,7,8,9]
def SplitSets(iterable,set_size):
row = 0
col = 0
for elem in iterable:
yield row, col, elem
if col == set_size - 1:
row = row+1
col = (col + 1) % set_size
for a,b,c in SplitSets(items,3):
print a,b,c
预期输出为
1,2,3
4,5,6
7,8,9
不多解释,只用分模求行列号
items = [1,2,3,4,5,6,7,8,9]
def SplitSets(iterable,set_size):
#return a generator
return ((i/set_size, i%set_size,e) for i,e in enumerate(iterable))
for a,b,c in SplitSets(items,3):
print a,b,c
类似的代码是:
items = [1,2,3,4,5,6,7,8,9]
def SplitSets(iterable,set_size):
for i, elem in enumerate(iterable):
yield i/set_size, i%set_size, elem
for a,b,c in SplitSets(items,3):
print a,b,c
一种解决方案是使用 itertools:
from itertools import count, cycle, izip
def split_sets(iterable, set_size):
for a, b, c in izip(count(), cycle(range(set_size)), items):
yield a // set_size, b, c
items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
set_size = 3
for a, b, c in split_sets(items, set_size):
print a, b, c
讨论
- 对于第一列 (a),我们调用
count()
,其中 returns 0, 1, 2, 3, 4...然后我们将 a 除以 set_size 得到我们想要的
- 对于第二列,
range(set_size)
returns [0, 1, 2] for set_size of 3. cycle()
函数然后一遍又一遍地重复这个序列。
- 最后一列无需解释
- 现在,如果我们将这些列和
izip
(比 Python 2.x 的 zip 更有效)放在一起,我们将得到我们想要的。
我正在尝试将列表拆分为枚举集,我有一个实现似乎可以满足我的要求,但感觉不是很“pythonic”有没有更好的方法?
下面的示例将项目拆分为最大大小为 3 的集合,returns 项目中的每个项目以及集合编号和集合索引
items = [1,2,3,4,5,6,7,8,9]
def SplitSets(iterable,set_size):
row = 0
col = 0
for elem in iterable:
yield row, col, elem
if col == set_size - 1:
row = row+1
col = (col + 1) % set_size
for a,b,c in SplitSets(items,3):
print a,b,c
预期输出为
1,2,3
4,5,6
7,8,9
不多解释,只用分模求行列号
items = [1,2,3,4,5,6,7,8,9]
def SplitSets(iterable,set_size):
#return a generator
return ((i/set_size, i%set_size,e) for i,e in enumerate(iterable))
for a,b,c in SplitSets(items,3):
print a,b,c
类似的代码是:
items = [1,2,3,4,5,6,7,8,9]
def SplitSets(iterable,set_size):
for i, elem in enumerate(iterable):
yield i/set_size, i%set_size, elem
for a,b,c in SplitSets(items,3):
print a,b,c
一种解决方案是使用 itertools:
from itertools import count, cycle, izip
def split_sets(iterable, set_size):
for a, b, c in izip(count(), cycle(range(set_size)), items):
yield a // set_size, b, c
items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
set_size = 3
for a, b, c in split_sets(items, set_size):
print a, b, c
讨论
- 对于第一列 (a),我们调用
count()
,其中 returns 0, 1, 2, 3, 4...然后我们将 a 除以 set_size 得到我们想要的 - 对于第二列,
range(set_size)
returns [0, 1, 2] for set_size of 3.cycle()
函数然后一遍又一遍地重复这个序列。 - 最后一列无需解释
- 现在,如果我们将这些列和
izip
(比 Python 2.x 的 zip 更有效)放在一起,我们将得到我们想要的。