我想使用列表I5
执行索引操作来创建一个新的列表I6
。然而,在符号上似乎有一个错误。
逻辑如下:
I6=[[(I5[0][0]),(I5[0][1]-I5[0][0])],[(I5[1][0]),(I5[1][1]-I5[1][0])],...]
代码是:
I5 = [[(0.5, -0.5), (1.5, -0.5)], [(0.5, -0.5), (0.5, -1.5)], [(1.5, -0.5), (1.5, -1.5)], [(0.5, -1.5), (1.5, -1.5)]]
for i in range (0,len(I5)):
I6=I5[i][0]-I5[i][1]
print(I6)
错误是:
in <module>
I6=I5[i][0]-I5[i][1]
TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'
期望输出为:
I6 = [[(0.5, -0.5), (1, 0)], [(0.5, -0.5), (0, -1)], [(1.5, -0.5), (0, -1)], [(0.5, -1.5), (1, 0)]]
尝试:
I5 = [
[(0.5, -0.5), (1.5, -0.5)],
[(0.5, -0.5), (0.5, -1.5)],
[(1.5, -0.5), (1.5, -1.5)],
[(0.5, -1.5), (1.5, -1.5)],
]
I6 = []
for i in range(0, len(I5)):
I6.append(
[I5[i][0], (I5[i][1][0] - I5[i][0][0], I5[i][1][1] - I5[i][0][1])]
)
print(I6)
打印:
[
[(0.5, -0.5), (1.0, 0.0)],
[(0.5, -0.5), (0.0, -1.0)],
[(1.5, -0.5), (0.0, -1.0)],
[(0.5, -1.5), (1.0, 0.0)],
]
我认为这段代码有效。
I5 = [[(0.5, -0.5), (1.5, -0.5)], [(0.5, -0.5), (0.5, -1.5)], [(1.5, -0.5), (1.5, -1.5)], [(0.5, -1.5), (1.5, -1.5)]]
I6 = []
for i in range (0,len(I5)):
I6.append([])
I6[i].append(I5[i][0])
toadd = []
toadd.append(I5[i][1][0]-I5[i][0][0])
toadd.append(I5[i][1][1]-I5[i][0][1])
I6[i].append(toadd)
print(I6)
一个简洁的方法是:
I6 = [[s[0], tuple(y - x for x, y in zip(s[0], s[1]))] for s in I5]
给了:
[[(0.5, -0.5), (1.0, 0.0)], [(0.5, -0.5), (0.0, -1.0)], [(1.5, -0.5), (0.0, -1.0)], [(0.5, -1.5), (1.0, 0.0)]]
更短(但可能不那么透明):
I6 = [[s[0], tuple(y - x for x, y in zip(*s))] for s in I5]
这似乎给出了期望的输出,尽管零值是浮点数而不是问题中暗示的整型。
I5 = [[(0.5, -0.5), (1.5, -0.5)], [(0.5, -0.5), (0.5, -1.5)], [(1.5, -0.5), (1.5, -1.5)], [(0.5, -1.5), (1.5, -1.5)]]
I6 = []
for e1, e2 in I5:
I6.append([e1, (e2[0]-e1[0], e2[1]-e1[1])])
print(I6)
输出:
[[(0.5, -0.5), (1.0, 0.0)], [(0.5, -0.5), (0.0, -1.0)], [(1.5, -0.5), (0.0, -1.0)], [(0.5, -1.5), (1.0, 0.0)]]
您可以使用pandas:
I5 = [[(0.5, -0.5), (1.5, -0.5)], [(0.5, -0.5), (0.5, -1.5)], [(1.5, -0.5), (1.5, -1.5)], [(0.5, -1.5), (1.5, -1.5)]]
import pandas as pd
df = pd.DataFrame(I5)
df[2] = df[0].map(lambda x: x[0])
df[3] = df[0].map(lambda x: x[1])
df[4] = df[1].map(lambda x: x[0])
df[5] = df[1].map(lambda x: x[1])
将返回:
#df:
0 1 2 3 4 5
0 (0.5, -0.5) (1.5, -0.5) 0.5 -0.5 1.5 -0.5
1 (0.5, -0.5) (0.5, -1.5) 0.5 -0.5 0.5 -1.5
2 (1.5, -0.5) (1.5, -1.5) 1.5 -0.5 1.5 -1.5
3 (0.5, -1.5) (1.5, -1.5) 0.5 -1.5 1.5 -1.5
,然后你可以根据其他列创建你想要的新列,我认为比使用嵌套列表更容易:
df[6] = df[3] - df[2]
0 1 2 3 4 5 6
0 (0.5, -0.5) (1.5, -0.5) 0.5 -0.5 1.5 -0.5 -1.0
1 (0.5, -0.5) (0.5, -1.5) 0.5 -0.5 0.5 -1.5 -1.0
2 (1.5, -0.5) (1.5, -1.5) 1.5 -0.5 1.5 -1.5 -2.0
3 (0.5, -1.5) (1.5, -1.5) 0.5 -1.5 1.5 -1.5 -2.0