Reputation: 313
I have a list of items that I need to actually be a list of lists. All the conversion methods I have seen convert the non-list items to lists of individual characters ["12", "cat", 87]
to [['1', '2'], ['c', 'a', 't'], ['8', '7']]
instead of [['12'], ['cat'], [87]]
. The following works,
v_Data = ["12", "cat", 87]
for index, i in enumerate(v_Data):
if type(i) != list:
v_Data[index] = [i]
print(v_Data) ## [['12'], ['cat'], [87]]
Is there a better way to do this?
Using Python 2.7
Upvotes: 1
Views: 847
Reputation: 2401
You can use a list comprehension:
v_Data = ["12", "cat", 87]
new = [[x] for x in v_Data]
Similar to:
v_Data = ["12", "cat", 87]
new = []
for x in v_Data:
new.append([x])
Upvotes: 0
Reputation: 2788
you can do :
>>> a=["12", "cat", 87]
>>> b=[[i] for i in a]
>>> b
[['12'], ['cat'], [87]]
EDIT : if there is already list in your list :
>>> a=["12", "cat", 87, [23]]
>>> b=[[i] if type(i) is not list else i for i in a]
>>> b
[['12'], ['cat'], [87], [23]]
Upvotes: 1
Reputation: 214957
You can use list-comprehension
:
v_Data = ["12", "cat", 87]
[v if isinstance(v, list) else [v] for v in v_Data]
# [['12'], ['cat'], [87]]
Upvotes: 3