3

I have to change a list of values into multiple array set as shown below:

list_train_data = [u'Class 1',
 u'Class 2',
 u'Class 3',
 u'Class 4',
 u'Class 5']

I need this value into an array like:

train_set = [['Class 1'],['Class 2'],['Class 3'],['Class 4'],['Class 5']]

If possible not use for loop.

3 Answers 3

7

Scince you added numpy tag, here is a numpy solution:

list_train_data = [u'Class 1',
 u'Class 2',
 u'Class 3',
 u'Class 4',
 u'Class 5']

import numpy as np
np.array(list_train_data, "O")[:, None]

the result is:

array([[u'Class 1'],
       [u'Class 2'],
       [u'Class 3'],
       [u'Class 4'],
       [u'Class 5']], dtype=object)
Sign up to request clarification or add additional context in comments.

Comments

7

Use a list comprehension:

train_set = [[x] for x in list_train_data]

Demo:

>>> list_train_data = [u'Class 1', u'Class 2', u'Class 3', u'Class 4', u'Class 5']
>>> [[x] for x in list_train_data]
[[u'Class 1'], [u'Class 2'], [u'Class 3'], [u'Class 4'], [u'Class 5']]

1 Comment

Technically, this is still using a loop.
1

There is of course another way without using loops, and thats using the map function:

>>> list_train_data = ['Class 1',
                   'Class 2',
                   'Class 3',
                   'Class 4',
                   'Class 5']
>>> map(lambda x: [x], list_train_data)
[['Class 1'], ['Class 2'], ['Class 3'], ['Class 4'], ['Class 5']]

No loops whatsoever. However this is slower than a LC. But still no for loops to be seen.

2 Comments

map with lambda is actually slower than a LC. Python List Comprehension Vs. Map
@hcwhsa but still no for :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.