如何成对合并多个数组

2024-06-13 08:22:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我对将数组“配对”为一个数组(按索引)有问题。举个例子:

输入:

inputArray = [[0, 1, 2, 3, 4], [2, 3, 5, 7, 8], [9, 6, 1]]

预期产量:

outputArray = 
[[0,2,9],
[1,3,6],
[2,5,1],
[3,7,chooseRandom()],
[4,8,chooseRandom()]]

问题:

  1. 如何避免“超出范围”“索引错误”问题
  2. 如何编写chooseRandom()来选择N个邻居

答案:

  1. [SOLVED]由@jornsharpe&;@Christian&;@decentcy提供的解决方案 预期

澄清:

我的意思是: enter image description here

我正在使用python,但是可以用任何语言自由地分享您的想法。你知道吗


Tags: 答案错误数组解决方案例子amp产量christian
3条回答

下面是我在python3.4中解决这个问题的方法。我真的不知道你所说的“选择邻居”是什么意思,但写起来应该很容易,不管你想在下面的上下文。你知道吗

inputArray = [[0, 1, 2, 3, 4], [2, 3, 5, 7, 8], [9, 6, 1]]

import itertools

zipped = itertools.zip_longest(*inputArray, fillvalue=None)
outputArray = [list(item) for item in zipped]
# [[0, 2, 9], [1, 3, 6], [2, 5, 1], [3, 7, None], [4, 8, None]]

# Now replace the sentinel None in our sublists
for sublist in outputArray:
    for i, element in enumerate(sublist):
        if element is None:
            sublist[i] = chooseRandom()

print(outputArray)

虽然不是最具python风格的方式,但您可以尝试使用此代码,请阅读下面代码中的注释:

import itertools, random

inputArray = [ [0, 1, 2, 3, 4], [2, 3, 5, 7, 8], [9, 6, 1] ]
outputArray = []

max_length = max(len(e) for e in inputArray) # maximum length of the sublists in <inputArray>
i = 0 # to keep the index of sublists of <outputArray>

for j in range(max_length):
    outputArray.append([]) # add new sublist
    for e in inputArray: # iterate through each element of <inputArray>
        try:
            outputArray[i].append(e[j]) # try to append the number, if an exception is raised
                                        # then the code in the <except> clause will be executed
        except IndexError as e:
            outputArray[i].append(random.randint(0, 10)) # add the random number
    i += 1 # increase the sublists index on each iteration

print outputArray
# [[0, 2, 9], [1, 3, 6], [2, 5, 1], [3, 7, 3], [4, 8, 7]]

注意:

你可能想换个零件

random.randint(0, 10)

获取“N邻居”。你知道吗

我认为以下几点可以满足您的要求:

from itertools import izip_longest # 'zip_longest' in Python 3.x
from random import choice

# Step 1
outputArray = list(map(list, izip_longest(*inputArray)))
# Step 2
for index, arr in enumerate(outputArray):
    if any(item is None for item in arr):
        valid = [item for item in arr if item is not None]
        outputArray[index] = [choice(valid) if item is None else item 
                              for item in arr]

这有两个步骤:

  1. inputArray的所有子列表合并到最长子数组的长度,填充None[[0, 2, 9], [1, 3, 6], [2, 5, 1], [3, 7, None], [4, 8, None]];并且
  2. 通过outputArray查找任何包含None的子列表,并用子列表中其他非None项的随机选择替换None。你知道吗

输出示例:

[[0, 2, 9], [1, 3, 6], [2, 5, 1], [3, 7, 3], [4, 8, 8]]

相关问题 更多 >