假设我有一份清单:
['apples','oranges','bananas','pineapples','grapes','mushrooms','milk']
我如何将其拆分为每个n
项目的列表(在我的示例3
每个子列表项目中)并将剩余部分均匀地添加到尽可能多的子列表中?
我的第一个解决方案是将每个组拆分为我想要的数量,取最后一个列表,然后根据它的大小将其添加到每个第一组,但我会硬编码这些值..
我甚至不知道如何从逻辑上开始思考这个问题。
编辑:
结果:
[['apples','oranges','bananas','milk'],['pineapples','grapes','mushrooms']]
答案 0 :(得分:2)
你可以试试这个
a = ['apples', 'oranges', 'bananas', 'pineapples', 'grapes', 'mushrooms', 'milk']
n = 3 # No of groups
[a[i::3] for i in range(n)]
输出
[['apples', 'pineapples', 'milk'], ['oranges', 'grapes'], ['bananas', 'mushrooms']]
答案 1 :(得分:0)
这样的事情:
li=['apples','oranges','bananas','pineapples','grapes','mushrooms','milk']
n=3
for chunk in [li[i:i+n] for i in range(0, len(li), n)]:
print chunk
打印:
['apples', 'oranges', 'bananas']
['pineapples', 'grapes', 'mushrooms']
['milk']
或者你可以沿着这些方向做点什么:
def partition(lst, n):
''' divide lst in n nearly even size chunks '''
n=min(len(lst),n)
q, r = divmod(len(lst), n)
indices = [q*i + min(i, r) for i in xrange(n+1)]
return [lst[indices[i]:indices[i+1]] for i in xrange(n)]
for n in range(1,5):
print n, partition(li, len(li)/n+1)
打印:
1 [['apples'], ['oranges'], ['bananas'], ['pineapples'], ['grapes'], ['mushrooms'], ['milk']]
2 [['apples', 'oranges'], ['bananas', 'pineapples'], ['grapes', 'mushrooms'], ['milk']]
3 [['apples', 'oranges', 'bananas'], ['pineapples', 'grapes'], ['mushrooms', 'milk']]
4 [['apples', 'oranges', 'bananas', 'pineapples'], ['grapes', 'mushrooms', 'milk']]
答案 2 :(得分:0)
import math
lst = ['apples','oranges','bananas','pineapples','grapes','mushrooms','milk']
new_lst = []
sets = 2
if len(lst)/sets > 0 :
iterate = math.floor(len(lst)/sets)
else:
iterate = math.ceil(len(lst)/sets)
for x in range(iterate):
new_lst.append([])
for y in range(sets):
new_lst[-1].append(lst.pop(0))
for x in range(len(lst)):
new_lst[0].append(lst.pop(0))
print(new_lst)