为什么拆分结果中有“数组”?(Python)

2024-04-23 22:00:30 发布

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

我想把一个数组拆分成子数组。原始数据为:

['4 2','1 4','1 4']
['4 1','4 1','3 1']
['3','2','1']

我想得到的结果是:

['4','1','1']
['2','4','4']
['4','4','3']
['1','1','1']
['3','2','1']

所以我的代码是:

raw = [['4 2','1 4','1 4'],['4 1','4 1','3 1'],['3','2','1']]
newraw =[]
for item in raw:
    #print item
    numberOfRow = len(item[0].split(" "))
    temp = np.empty((numberOfRow,5))


    for i in range(len(item)):
        test = item[i].split(" ")
        for j in range(len(test)):
            temp[j,i]=test[j]
    for it in temp:
        newraw.append(it)
print newraw

当我print newraw时,我发现问题:(1)结果包含非整数,(2)结果包含[array([...])...,但我不知道为什么。你知道吗

那么,有什么解决办法,或者有什么简单的方法可以得到我想要的结果吗?~谢谢~


Tags: intestfor原始数据rawlenrangeit
3条回答

你有点太复杂了,可能我也是。我将在raw上迭代,然后为每个内部数组创建一个helper容器(dict),它将作为值保存在提取的数组中,作为键在文本数组中的位置。你知道吗

raw = [['4 2','1 4','1 4'],['4 1','4 1','3 1'],['3','2','1']]

res = []

for inner_arr in raw:
    temp_container = {}
    for el in inner_arr:
        for idx, splited in enumerate(el.split()):
            if idx in inner:
                temp_container[idx].append(splited)
            else:
                temp_container[idx] = [splited]

    res += temp_container.values()

print(res)

这将适用于“文本数组”中任意数量的元素。你知道吗

在Python2中有一行:-)

>>> from itertools import chain
>>> list(chain(*[zip(*[x.split() for x in item]) for item in raw]))
[('4', '1', '1'), ('2', '4', '4'), ('4', '4', '3'), ('1', '1', '1'), ('3', '2', '1')]

那条线是干什么的?让我们把它分解一下(我假设有链的知识,列表理解等):

  • 最简单的例子,然后我们将在此基础上继续。你知道吗

    >>> raw = ['4 2','1 4','1 4']
    >>> zip(*[x.split() for x in raw])
    [('4', '1', '1'), ('2', '4', '4')]
    

    zip执行某种矩阵转置操作。举个简单的例子,试试纸笔法。这并不难。

  • 接下来,让我们在整个列表中尝试:

    >>> raw = [['4 2','1 4','1 4'],['4 1','4 1','3 1'],['3','2','1']]
    >>> [zip(*[x.split() for x in item]) for item in raw]
    [[('4', '1', '1'), ('2', '4', '4')], [('4', '4', '3'), ('1', '1', '1')], [('3', '2', '1')]]
    
  • 很近,让我们把它锁起来!你知道吗

    >>> raw = [['4 2','1 4','1 4'],['4 1','4 1','3 1'],['3','2','1']]
    >>> from itertools import chain
    >>> list(chain(*[zip(*[x.split() for x in item]) for item in raw]))
    [('4', '1', '1'), ('2', '4', '4'), ('4', '4', '3'), ('1', '1', '1'), ('3', '2', '1')]
    

你就不能这样做吗?你知道吗

x = [['4 2','1 4','1 4'],
['4 1','4 1','3 1'],
['3','2','1']]

res = []
for i in x:
    res.extend(map(list, zip(*(j.split(" ") for j in i))))

如果您不介意listtuples,那么map调用可能会丢失。我也不确定你是不是想把所有的值都转换成整数。您的示例输出没有显示这一点,因此我假定您不需要这样做。你知道吗

输出:

[['4', '1', '1'], ['2', '4', '4'], ['4', '4', '3'], ['1', '1', '1'], ['3', '2', '1']]

相关问题 更多 >