Python列表合并

时间:2013-03-19 11:45:47

标签: python

我正在获得这样的列表输出,我想明确区分列表 这样我就可以单独访问每个列表了我该怎么做

for Book in rootNode.getBooks():
    CompareTables=[]
    CompareTables.append(Book.getName())
    for Table in Book.getTables():
        CompareTables.append(Table.getName())
    print CompareTables

Output:

['Document', 'A','B','C']
['Document', 'A','B','C','D','E','F']

我想要这样的输出:

print CompareTables1

Output:

 ['Document', 'A','B','C']

print CompareTables2

 ['Document', 'A','B','C','D','E','F']

2 个答案:

答案 0 :(得分:3)

创建一个新列表,将每个图书列表添加到:

all_compare_tables = []
for Book in rootNode.getBooks():
    CompareTables=[]
    CompareTables.append(Book.getName())
    for Table in Book.getTables():
        CompareTables.append(Table.getName())
    all_compare_tables.append(CompareTables)

print all_compare_tables[0]
print all_compare_tables[1]

# better yet, loop:

for compare_tables in all_compare_tables:
    print compare_tables

或者,您可以使用字典:

all_compare_tables = {}
for i, Book in enumerate(rootNode.getBooks(), 1):
    CompareTables=[]
    CompareTables.append(Book.getName())
    for Table in Book.getTables():
        CompareTables.append(Table.getName())
    all_compare_tables['CompareTables{}'.format(i)] = CompareTables

以上示例生成的密钥为CompareTables1CompareTables2等,但您可能会考虑更好的名称。

然后打印这些:

print all_compare_tables['CompareTables1']
print all_compare_tables['CompareTables2']

或循环遍历all_compare_tables.keys()all_compare_tables.values()序列。

答案 1 :(得分:0)

嗯,dict是针对这种情况制作的:

CompareTables = {}
for Book in rootNode.getBooks():
    book_name = Book.getName()
    CompareTables[book_name] = []
    for Table in Book.getTables():
        CompareTables[book_name].append(Table.getName())
    print CompareTables

这里您的2本书似乎有相同的标题Document,因此您可以使用索引来区分它们:

CompareTables = {}
for i, Book in enumerate(rootNode.getBooks(), 1):
    book_name = Book.getName() + str(i)
    CompareTables[book_name] = []
    for Table in Book.getTables():
        CompareTables[book_name].append(Table.getName())
    print CompareTables