简体   繁体   English

将元组操作成元组列表

[英]manipulate tuple into a list of tuples

I have the following variable for class label in my dataset:我的数据集中有 class label 的以下变量:

y = np.array([3, 3, 3, 2, 3, 1, 3, 2, 3, 3, 3, 2, 2, 3, 2])

To determine the number of each class, I do:为了确定每个 class 的数量,我这样做:

np.unique(y, return_counts=True)
(array([1, 2, 3]), array([1, 5, 9]))

How then do I manipulate this into a list of tuples for (label, n_samples) ?那么我如何将其操作为(label, n_samples)的元组列表? So that I have:这样我就有了:

[ (1,1), (2,5), (3,9) ]

If you want a simple list, use zip :如果您想要一个简单的列表,请使用zip

out = list(zip(*np.unique(y, return_counts=True)))

Output: [(1, 1), (2, 5), (3, 9)] Output: [(1, 1), (2, 5), (3, 9)]

Alternatively, you can create an array with:或者,您可以创建一个数组:

np.vstack(np.unique(y, return_counts=True)).T

Output: Output:

array([[1, 1],
       [2, 5],
       [3, 9]])
list_1 = ['a', 'b', 'c']
list_2 = [1, 2, 3]

# option 1
list_of_tuples = list(
    map(
        lambda x, y: (x, y),
        list_1,
        list_2
    )
)

#option 2
list_of_tuples = [
    (list_1[index], list_2[index]) for index in range(len(list_1))
]

# option 3
list_of_tuples = list(zip(list_1, list_2))

print(list_of_tuples)
# output is [('a', 1), ('b', 2), ('c', 3)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM