我有一个这种格式的数组:
val = [[1302, 303, 168, 536],
[1424, 360, 226, 677],
[776, 321, 194, 509],
[1066, 276, 191, 571]]
我通过以下方式提取数组的第一个和第二个元素:
x = [col for col in list(zip(*val))[0]]
y = [col for col in list(zip(*val))[1]]
创建一个空集:
points = set()
使用列表组合创建元组:
center = tuple(zip(x,y))
将列表添加到点数据集中:
points.add(center)
最后一次尝试打印一个列表:
for point in points:
print(point)
我得到以下结果:
((1302, 303), (1424, 360), (776, 321), (1066, 276))
但是我希望它可以打印:
首先,(1302, 303)
第二,(1424, 360)
以此类推。
有人可以指导我怎么做吗?
谢谢!
答案 0 :(得分:1)
只需使用双for循环
#Iterate over the set
for point in points:
#Iterate on each point
for item in point:
print(item)
这将输出
(1302, 303)
(1424, 360)
(776, 321)
(1066, 276)
要在一个循环中打印它,您需要将points
设置为一维列表
val = [[1302, 303, 168, 536],
[1424, 360, 226, 677],
[776, 321, 194, 509],
[1066, 276, 191, 571]]
x = [col for col in list(zip(*val))[0]]
y = [col for col in list(zip(*val))[1]]
points = set()
center = tuple(zip(x,y))
points.add(center)
#Convert set to a 1-D list
points = list(*points)
for point in points:
print(point)
这将输出
(1302, 303)
(1424, 360)
(776, 321)
(1066, 276)
或者没有循环的单线print
val = [[1302, 303, 168, 536],
[1424, 360, 226, 677],
[776, 321, 194, 509],
[1066, 276, 191, 571]]
x = [col for col in list(zip(*val))[0]]
y = [col for col in list(zip(*val))[1]]
points = set()
center = tuple(zip(x,y))
points.add(center)
#One liner print
print(*list(*points), sep='\n')
答案 1 :(得分:1)
您可以遍历原始列表:
for x in val:
print(tuple(x[:2]))
或者从您的points
使用拆包并传递sep
:
points = ((1302, 303), (1424, 360), (776, 321), (1066, 276))
print(*points, sep='\n')
# (1302, 303)
# (1424, 360)
# (776, 321)
# (1066, 276)
答案 2 :(得分:1)
我觉得这太复杂了:
x = [col for col in list(zip(*val))[0]]
y = [col for col in list(zip(*val))[1]]
相反,您可以这样做:
x = [col[0] for col in val]
y = [col[1] for col in val]
然后,创建您的点数据结构:
points = set([(i, j) for i, j in zip(x, y)])
打印您的观点:
for point in points:
print(point)