Python:扩展数组保持方括号



我试图扩展一个列表以添加其他值,但在结果中,它一直显示上一个列表的末尾。

def landmarksPoint():
landmarkPoints = []
# Check for range of landmarks (0 to 23) within the image, if all are displayed then continue to save the file.
for n in range(pointNumber):
# Split each line and column to save to text file and save to landmarkPoints Array.
x = landmarks.part(n).x
y = landmarks.part(n).y
# Print each line for testing and append it to array.
print("x:", x, " y:", y)
landmarkPoints.append((x, y))
return landmarkPoints

for hand in hands:
landmarks = predictor(imageGray1, composite1)
points1.append(landmarksPoint())
print(points1)
boundaryLoc = (1,1), (700,1), (1590, 1), (1590,500), (1590, 1190), (700, 1190), (1, 1190), (1,500)
points1.extend(boundaryLoc)
print(points1)

OUTPUT: 
[[(992, 191), (1178, 337), (895, 702), (859, 873), (831, 991), (836, 514), (794, 627), (762, 768), (744, 900), (770, 396), (728, 479), (705, 586), (1213, 458), (690, 703), (773, 229), (803, 140), (1228, 147), (1281, 543), (1082, 471), (1027, 576), (996, 712), (970, 841), (933, 966), (922, 563)], (1, 1), (700, 1), (1590, 1), (1590, 500), (1590, 1190), (700, 1190), (1, 1190), (1, 500)]

文档说list.extend()用一个可迭代的参数的内容扩展了调用对象。

因此,points1.extend(boundaryLoc)使用元组boundaryLoc的内容来扩展列表points1(您可以通过检查type(boundaryLoc)的结果来验证boundaryLoc是元组的元组(。

这意味着boundaryLoc中包含的每个元组实际上都将附加到points1,这正是您的输出所显示的内容。

如果要将元组列表附加到points1,可以执行以下操作:

boundaryLoc = [(1,1), (700,1), (1590, 1), (1590,500), (1590, 1190), (700, 1190), (1, 1190), (1,500)]
points1.append(boundaryLoc)

注意,我们已经明确地使boundaryLoc成为元组的列表(而不是元组(,并且我们使用append()而不是extend()

如果你真的想使用extend(),你可以这样做:

points1.extend([boundaryLoc])

最新更新