如何将数组切成某些子数组?

时间:2019-06-25 12:15:07

标签: python arrays slice

我有一个像这样的数组

[
    {'name':'a'},
    {'name':'b'},
    {'name':'c'},
    {'name':'d'},
    {'name':'e'},
    {'name':'f'}
]

数组长度为6,现在我想将其拆分为4个子数组,我希望结果会像

[
    [
         {'name':'a'},
         {'name':'e'}
    ],
    [
         {'name':'b'},
         {'name':'f'}
    ],
    [
         {'name':'c'}
    ],
    [
         {'name':'d'}
    ]
]

我可以使用循环来做到这一点,我想知道还有其他聪明的方法吗?

我的不好,也许我不清楚,这是我的代码:

def uploadSheets(servers, sheets):
serverLen = len(servers.keys())
sheetsLen = len(sheets)
index = 0
count = int(cookieLen / serverLen)
left = int(sheetsLen % serverLen)
for key in servers.keys():
    ip = servers[key]
    remoteExecute(user=user, ip=ip, command='rm /home/pdd/sheets/*', passwd=passwd)
    for j in range(count):
        localPath = '../deploy/' + sheets[index * count + j]
        remotePath = '/home/pdd/sheets/'
        fileTransfer(localPath=localPath, ip=ip, user=user, destPath=remotePath, passwd=passwd)
    index += 1
for i in range(left):
    localPath = './deploy/' + sheets[index * count + i]
    remotePath = '/home/pdd/sheets/'
    ip = servers[list(servers.keys())[i]]

print('finish')

我有一组服务器,每天我将越来越多的文件上传到每台服务器而没有重复。而且有一种模式是,彼此克隆的文件名可以更好地发送到另一台服务器。

就像我有101个苹果,20个篮子一样,我将苹果从busket1放到busket1到busket20,最后,busket1将有6个苹果,其他有5个。

1 个答案:

答案 0 :(得分:0)

根据逻辑如何将元素排列在一起,您可以执行以下操作:

list1 = [{'name':'a'},{'name':'b'},{'name':'c'},{'name':'d'},{'name':'e'},{'name':'f'}]
logic = [[0,4], [1,5], [2,3]]
print([[list1[y] for y in x] for x in logic])

输出

[[{'name': 'a'}, {'name': 'e'}],
 [{'name': 'b'}, {'name': 'f'}],
 [{'name': 'c'}, {'name': 'd'}]]