我想知道您是否可以帮助我了解如何为此问题编写解决方案,
我有两个这样的列表:
list1 = [[x1, y1], [x2, y2], [x3, y3]]
list2 = [[z1, m1, m2, m3], [z2, m1, m2, m3], [z3, m1, m2, m3]]
我想要的输出是:
list3 = [[z1, (m1/y1), (m2/y2), (m3/y3)],
[z2, (m1/y1), (m2/y2), (m3/y3)],
[z3, (m1/y1), (m2/y2), (m3/y3)]]
我所拥有的是2个列表列表,我想用list1中每个列表中的第二项除以list2中的值(除了第一个,因为它是一个字符串)。
代码是做什么的?我试过制作循环来解决它,但我还没有取得多大成功。
非常感谢任何帮助!
答案 0 :(得分:0)
重新排列list1
个项目,然后它就是迭代和元组解包:
list3 = []
for ((z1,m1,m2,m3),(y1,y2,y3)) in [[zm, [y for (x,y) in list1]] for zm in list2]:
list3.append([z1,(m1/y1),(m2/y2),(m3/y3)])
以上代码也可以作为列表理解编写:
[[z1,(m1/y1),(m2/y2),(m3/y3)] for ((z1,m1,m2,m3),(y1,y2,y3)) in [[zm, [y for (x,y) in list1]] for zm in list2]]
答案 1 :(得分:0)
你可以试试这个。为了答案,我已经用适当的值定义了变量。
x1 = 's'
x2 = 't'
x3 = 'u'
y1 = 2
y2 = 4
y3 = 6
z1 = 'a'
z2 = 'b'
z3 = 'c'
m1 = 4
m2 = 8
m3 = 12
list1 = [[x1, y1], [x2, y2], [x3, y3]]
list2 = [[z1, m1, m2, m3], [z2, m1, m2, m3], [z3, m1, m2, m3]]
list3 = []
for sub in list2:
temp_list = [sub[0]]
for indx, num in enumerate(sub[1:]):
temp_list.append((num//list1[indx][1],)) # single-element tuples need a trailing comma
list3.append(temp_list)
print(list3)
[['a', (2,), (2,), (2,)], ['b', (2,), (2,), (2,)], ['c', (2,), (2,), (2,)]]
答案 2 :(得分:0)
除了其他答案,如果你想要某种通用方式,
import numpy as np
list1 = [[0, 1], [2, 3], [4, 5]]
list2 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 8,7,6]]
s_l2=np.shape(list2)
for i in range(s_l2[0]):
for j in range(s_l2[1]):
if j!=0:
list3[i][j] = list2[i][j]/list1[j-1][1]