我试图在嵌套列表的this问题中使用已使用的结构,但我很困惑,不知道如何弄明白。假设要减去两个列表a = ['5', '35.1', 'FFD']
和b = ['8.5', '11.3', 'AMM']
,以下代码用于达到等式c = b - a:
diffs = []
for i, j in zip(a, b):
try:
diffs.append(str(float(j) - float(i)))
except ValueError:
diffs.append('-'.join([j, i]))
>>> print(diffs)
['3.5', '-23.8', 'AMM-FFD']
我的问题是,如何通过考虑以下结构得到C = B-A:
A = [['X1','X2'],['52.3','119.4'],['45.1','111']]
B = [['Y1','Y2'],['66.9','65'],['99','115.5']]
C = [['Y1-X1','Y2-X2'],['14.6',' - 54.4'],['53.9','4.5']]
我如何处理每个内部列表的第一个和第二个元素,如:
Array 1 = ['Y1-X1', '14.6', '53.9'] Array 2 = ['Y2-X2', '-54.4', '4.5']
我感谢任何帮助。
答案 0 :(得分:1)
好吧,如果它保证列表总是嵌套2级,你可以简单地添加一个循环:
diffs_lists = []
for i, j in zip(a, b):
diffs = []
for k, l in zip(i, j):
try:
diffs.append(str(float(k) - float(l)))
except ValueError:
diffs.append('-'.join([k, l]))
diffs_lists.append(diffs)
要按照要求将结果分成两部分,只需使用zip:
zip(*diffs_lists)
答案 1 :(得分:1)
你只需要另一级循环:
res = []
for a, b in zip(A, B):
diffs = []
res.append(diffs)
for i, j in zip(a, b):
try:
diffs.append(str(float(j) - float(i)))
except ValueError:
diffs.append('-'.join([j, i]))
print(res)
#[['Y1-X1', 'Y2-X2'], ['14.600000000000009', '-54.400000000000006'], ['53.9', '4.5']]
print(list(zip(*res)))
#[('Y1-X1', '14.600000000000009', '53.9'), ('Y2-X2', '-54.400000000000006', '4.5')]
答案 2 :(得分:1)
diffs=[]
for sub_b, sub_a in zip(b, a):
curr = []
for atom_b, atom_a in zip(sub_b, sub_a):
try:
curr.append(float(atom_b) - float(atom_a))
except ValueError:
curr.append('-'.join([atom_b, atom_a]))
diffs.append(curr)
ans1, ans2 = zip(*diffs)
zip
函数也可用于解压缩迭代。
答案 3 :(得分:1)
假设您有一个list_diffs
函数,基本上就是您提供的代码:
list_diffs(a, b):
diffs = []
for i, j in zip(a, b):
try:
diffs.append(str(float(j) - float(i)))
except ValueError:
diffs.append('-'.join([j, i]))
return diffs
然后,您想要的C
只是一个列表,其元素在A
的元素和B
的元素之间是差异的。因此,以下内容为您提供了C
:
C = []
for i in range(len(A)):
C.append(list_diffs(A[i], B[i]))
获取第一个和第二个元素的列表:
array1 = [c[0] for c in C]
array2 = [c[1] for c in C]
答案 4 :(得分:0)
如果你需要使用任意数量的嵌套,你可以使用递归:
def subtract(x, y):
diffs = []
for a, b in zip(x, y):
try:
if isinstance(a, list):
diffs.append(subtract(a, b))
else:
diffs.append(str(float(b) - float(a)))
except ValueError:
diffs.append('-'.join([b, a]))
return diffs
正如其他人所指出的,zip
可用于解压缩:
res = subtract(A, B)
t1, t2 = zip(*res)
print(t1)
print(t2)
输出:
('Y1-X1', '14.6', '53.9')
('Y2-X2', '-54.4', '4.5')
答案 5 :(得分:0)
我用递归方法尝试它
A = [['X1','X2'],['52.3','119.4'],['45.1','111']]
B = [['Y1','Y2'],['66.9','65'],['99','115.5']]
C = [['Y1-X1','Y2-X2'],['14.6','-54.4'],['53.9','4.5']]
Array_a,Array_b = [[] for __ in range(2)]
def diff(B,A):
_a = 0
for b,a in zip(B,A):
if isinstance(b,list):
diff(b,a)
else:
try:
Array_b.append(float(b)-float(a)) if _a else Array_a.append(float(b)-float(a))
_a = True
except (ValueError,TypeError) as e:
Array_b.append("{0}-{1}".format(b,a)) if _a else Array_a.append("{0}-{1}".format(b,a))
_a = True
return (Array_a,Array_b)
print (diff(B,A))
>>>(['Y1-X1', 14.600000000000009, 53.9], ['Y2-X2', -54.400000000000006, 4.5])