S_McC
S_McC

Reputation: 39

nesting a series of lists within a list - python

Originally this was lists within a list:

print results

[['aaa664847', 'Completed', 'location', 'mode', '2014-xx-ddT20:00:00.000']
['aaa665487', 'Completed', 'location', 'mode', '2014-xx-ddT19:00:00.000']
['aaa661965', 'Completed', 'location', 'mode', '2014-xx-ddT18:00:00.000']]

However, I needed to join the elements within the nested list which then prints out like this:

print results1

['aaa664847, Completed, location, mode, 2014-xx-ddT20:00:00.000']
['aaa665487, Completed, location, mode, 2014-xx-ddT19:00:00.000']
['aaa661965, Completed, location, mode, 2014-xx-ddT18:00:00.000']

I need to get the results back into a list within a list:

[['aaa664847, Completed, location, mode, 2014-xxddT20:00:00.000'],
['aaa665487, Completed, location, mode, 2014-xx-ddT19:00:00.000']]

Upvotes: 0

Views: 87

Answers (2)

Malik Brahimi
Malik Brahimi

Reputation: 16721

You mean something like this:

your_list = [[', '.join(i)] for i in your_list]

Now your list is equivalent to:

[['aaa664847, Completed, location, mode, 2014-xx-ddT20:00:00.000'], 
 ['aaa665487, Completed, location, mode, 2014-xx-ddT19:00:00.000'], 
 ['aaa661965, Completed, location, mode, 2014-xx-ddT18:00:00.000']]

To print these individually try:

for item in your_list:
    print item

# Output is as follows ...

['aaa664847, Completed, location, mode, 2014-xx-ddT20:00:00.000'] 
['aaa665487, Completed, location, mode, 2014-xx-ddT19:00:00.000'] 
['aaa661965, Completed, location, mode, 2014-xx-ddT18:00:00.000']

Upvotes: 0

jedwards
jedwards

Reputation: 30260

It's not really clear whether you're trying to get from results to results1 or from results1 to new_Result (i.e. back to results).

But consider:

import pprint

results = [
['aaa664847', 'Completed', 'location', 'mode', '2014-xx-ddT20:00:00.000'],
['aaa665487', 'Completed', 'location', 'mode', '2014-xx-ddT19:00:00.000'],
['aaa661965', 'Completed', 'location', 'mode', '2014-xx-ddT18:00:00.000']
]

# Go from results -> results1
results1 = [', '.join(x) for x in results]
pprint.pprint(results1)
#  ['aaa664847, Completed, location, mode, 2014-xx-ddT20:00:00.000',
#   'aaa665487, Completed, location, mode, 2014-xx-ddT19:00:00.000',
#   'aaa661965, Completed, location, mode, 2014-xx-ddT18:00:00.000']    


# Go from results1 to new_Result
new_Result = [x.split(', ') for x in results1]
pprint.pprint(new_Result)
#  [['aaa664847', 'Completed', 'location', 'mode', '2014-xx-ddT20:00:00.000'],
#   ['aaa665487', 'Completed', 'location', 'mode', '2014-xx-ddT19:00:00.000'],
#   ['aaa661965', 'Completed', 'location', 'mode', '2014-xx-ddT18:00:00.000']]

print results == new_Result    # True

Upvotes: 2

Related Questions