在列表中嵌套一系列列表 - python

时间:2015-03-07 23:53:21

标签: python list nested-lists

最初这是列表中的列表:

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']]

但是,我需要加入嵌套列表中的元素,然后打印出来:

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']

我需要将结果返回到列表中的列表中:

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

2 个答案:

答案 0 :(得分:2)

您是否想要从resultsresults1或从results1new_Result(即回到results)并不是很清楚。

但请考虑一下:

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

答案 1 :(得分:0)

你的意思是这样的:

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

现在您的列表相当于:

[['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']]

要单独打印,请尝试:

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']