[英]Convert List of list into tuple of tuples
I have a list of 2x1
matrices like:我有一个
2x1
矩阵的列表,例如:
[[[2.3], [2.4]], [[1.7], [1.6]], [[2.02], [2.33]]]
I need to convert it into a tuple of tuples, like:我需要将其转换为元组的元组,例如:
((2.3,2.4),(1.7,1.6),(2.02,2.33))
I know I can loop through the list and convert it manually, trying to check if there is a better-optimized way of doing it.我知道我可以遍历列表并手动转换它,尝试检查是否有更好的优化方法。
Using nested list comprehension:使用嵌套列表推导:
orig = [[[2.3], [2.4]], [[1.7], [1.6]], [[2.02], [2.33]]]
>>> tuple(tuple(e[0] for e in l) for l in orig)
((2.3, 2.4), (1.7, 1.6), (2.02, 2.33))
You can do it this way using numpy indexing and slicing that outer dimension.您可以使用 numpy 索引和切片该外部尺寸来做到这一点。
ma = [[[2.3], [2.4]], [[1.7], [1.6]], [[2.02], [2.33]]]
ama=np.array(ma) #incase it wasn't a numpy array since you mentioned numpy in tags
tuple(map(tuple,ama[:, :, 0].tolist()))
Output: Output:
((2.3, 2.4), (1.7, 1.6), (2.02, 2.33))
L = [[[2.3], [2.4]], [[1.7], [1.6]], [[2.02], [2.33]]]
tuple(tuple(l2[0] for l2 in l1) for l1 in L)
Output: Output:
((2.3, 2.4), (1.7, 1.6), (2.02, 2.33))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.