gpt4 book ai didi

python - 如何在Python中将数组与其数组元素合并?

转载 作者:行者123 更新时间:2023-12-01 09:09:27 30 4
gpt4 key购买 nike

我有一个如下所示的数组;

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]

所以,这不是预期的结果,我陷入了这一步。问题是,如何将数组与其父数组合并?

最佳答案

这是一种方法。

演示:

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]

关于python - 如何在Python中将数组与其数组元素合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51785824/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com