如何在Python中合并数组及其数组元素?

时间:2018-08-10 11:46:08

标签: python arrays merge

我有一个如下数组;

constants = ['(1,2)', '(1,5,1)', '1']

我想将数组转换成下面的样子;

constants = [(1,2), 1, 2, 3, 4, 5, 1]

为此,我尝试了一些操作;

from ast import literal_eval
import numpy as np
constants = literal_eval(str(constants).replace("'",""))
constants = [(np.arange(*i) if len(i)==3 else i) if isinstance(i, tuple) else i for i in constants]

输出为;

constants = [(1, 2), array([1, 2, 3, 4]), 1]

所以,这不是预期的结果,我被此步骤卡住了。问题是,如何将数组与其父数组合并?

4 个答案:

答案 0 :(得分:1)

这是一种方法。

演示:

from ast import literal_eval

constants = ['(1,2)', '(1,5,1)', '1']
res = []
for i in constants:                
    val = literal_eval(i)              #Convert to python object
    if isinstance(val, tuple):         #Check if element is tuple
        if len(val) == 3:              #Check if no of elements in tuple == 3
            val = list(val)
            val[1]+=1
            res.extend(range(*val))
            continue            
    res.append(val)
print(res)

输出:

[(1, 2), 1, 2, 3, 4, 5, 1]

答案 1 :(得分:0)

请使用以下代码解决上述解析:

from ast import literal_eval


constants = ['(1,2)', '(1,5,1)', '1']
processed = []

for index, c in enumerate(constants):
    parsed = literal_eval(c)
    if isinstance(parsed, (tuple, list)) and index != 0:
        processed.extend(range(1, max(parsed) + 1))
    else:
        processed.append(parsed)

print processed  # [(1, 2), 1, 2, 3, 4, 5, 1]

答案 2 :(得分:0)

我将假设这个问题非常直白,并且您始终希望对此进行转换:

SELECT 
EMP_DETAILS.EMP_NO, 
EMP_DETAILS.EMPID_NO, 
EMP_DETAILS.ADDR1, 
EMP_DETAILS.ADDR2, 
EMP_DETAILS.START_DTTM, 
EMP_DETAILS.END_DTTM, 
EMP_DETAILS.CREATE_DTTM, 
EMP_DETAILS.ARCHV_FLAG AS EMP_DET_ARCHV_FLAG, 
EMP.ARCHV_FLAG AS EMP_ARCHV_FLAG
FROM
EMP_DETAILS, EMP 
WHERE
EMP_DETAILS.EMP_NO = EMP.EMP_NO
AND ISNULL(EMP.ARCHV_FLAG,'N') = 'N'
AND ISNULL(EMP_DETAILS.ARCHV_FLAG,'N') = 'N'

UNION

SELECT 
EMP_DETAILS.EMP_NO, 
EMP_DETAILS.EMPID_NO, 
EMP_DETAILS.ADDR1, 
EMP_DETAILS.ADDR2, 
EMP_DETAILS.START_DTTM, 
EMP_DETAILS.END_DTTM, 
EMP_DETAILS.CREATE_DTTM, 
EMP_DETAILS.ARCHV_FLAG AS EMP_DET_ARCHV_FLAG, 
EMP.ARCHV_FLAG AS EMP_ARCHV_FLAG
FROM
EMP_DETAILS ,
EMP 
WHERE
EMP_DETAILS.EMP_NO = EMP.EMP_NO
AND
 not exists (select 'x'
                    from    STG_EMP_TEMP STG 
                    where   STG.EMP_NO = EMP_DETAILS.EMP_NO
                    )

对此:

constants = ['(a, b)', '(x, y, z)', 'i']

,使第二元组的范围为transformed = [(a,b), x, x+z, x+2*z, ..., y, i] x,步长为y。因此,最终的转换数组是第一个元素,然后是第二个元素定义的范围,然后是最后一个元素。最简单的方法就是逐步操作:

z

答案 3 :(得分:0)

我提出以下建议:

res = []
for cst in constants:

    if isinstance(cst,tuple) and (len(cst) == 3):
        #add the range to the list
        res.extend(range(cst[0],cst[1], cst[2]))
    else:
        res.append(cst)

res具有您想要的结果。 可能有一种更优雅的解决方法。