0

我得到这样的列表输出,我想明确区分列表,以便我可以分别访问每个列表我该怎么做

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

2 回答 2

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

上面的示例将键生成为CompareTables1,CompareTables2等,但也许您有更好的名字。

打印这些然后变成:

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

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

于 2013-03-19T11:49:55.300 回答
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
于 2013-03-19T11:51:42.003 回答