python-3.x 我不明白enumerate(0,0),(1,[])的输出

xytpbqjk  于 2023-06-25  发布在  Python
关注(0)|答案(2)|浏览(86)

这是我的输出:

[['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']]
(0, 0)
(1, ['apples', 'oranges', 'cherries', 'banana'])
(0, 1)
(1, ['Alice', 'Bob', 'Carol', 'David'])
(0, 2)
(1, ['dogs', 'cats', 'moose', 'goose'])

解释给我听

我不明白这个输出是什么意思(0,0),(1,[]),(0,1),…

当我将enumeratate添加到print_table()时,我得到了输出。
我的数据是3个列表的列表,为什么我得到5行输出?

下面的一切都只是额外的信息

这是我的代码:

def calculate_widht(data):
    col_width = [0] * len(data)
    word_lenght = 0
    for i, words in enumerate(data):
        # print(i)
        # print(words)
        word_lenght = 0
        for word in words:
            if word_lenght < len(word):
                word_lenght = len(word)               
                col_width[i]= word_lenght
    return col_width

def print_table(width, data):
    print(data)
    for words in enumerate(data):
        for word in enumerate(words):
            print(word)
                
            

def main():
    data = [['apples', 'oranges', 'cherries', 'banana'],
            ['Alice', 'Bob', 'Carol', 'David'],
            ['dogs', 'cats', 'moose', 'goose']]
    start = calculate_widht(data)
    return print_table(start, data)

if __name__ == '__main__':
    main()

这是我的练习:
编写一个名为printTable()的函数,它接受一个字符串列表的列表,并将其显示在一个组织良好的表格中,每一列都右对齐。假设所有内部列表将包含相同数量的字符串。
我的输出应该是这样的:

apples Alice  dogs
  oranges   Bob  cats
 cherries Carol moose
   banana David goose
qpgpyjmq

qpgpyjmq1#

要了解你得到的结果,你必须查看文档,特别是这里:
enumerate(iterable, start=0)
返回枚举对象。iterable必须是序列、迭代器或其他支持迭代的对象。enumerate()**返回的迭代器的__next__()方法返回一个元组,该元组包含计数(从start开始,默认为0)和通过迭代迭代获得的值。
所以,你的外部for-循环

for words in enumerate(data):

生成(int, list)-words形式的元组。您可以通过查看list(enumerate(data))print来轻松验证这一点。这意味着在下一级循环中

for word in enumerate(words):

你正在循环像enumerate((int, list))这样的东西,而不是像你期望的那样,循环内部列表的枚举。因此,每个第一word具有形式(0, int),并且每个第二个具有形式(1, list)。这导致以下印刷图案:

(0, 0)
(1, <first list>)
(0, 1)
(1, <second list>)
(0, 2
(1, <third list>)
...

你使用enumerate没有多大意义,你想用它实现什么还不清楚?看起来你得到的数据列。所以你可以尝试类似以下的方法:

def print_table(data):
    widths = [max(map(len, column)) + 2 for column in data]
    table = "\n".join(
        "".join(item.rjust(width) for item, width in zip(row, widths))
        for row in zip(*data)
    )
    print(table)

首先,通过获取其中字符串的最大长度来确定列的宽度,+ 2用于缓冲区,以使其看起来更好。然后使用zip获取行,用resp对字符串进行右对齐。width"".join它们,然后"\n".join沿着线中断如此构建的行。
结果

data = [['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],
        ['dogs', 'cats', 'moose', 'goose']]

apples  Alice   dogs
   oranges    Bob   cats
  cherries  Carol  moose
    banana  David  goose
6jjcrrmo

6jjcrrmo2#

使用enumerate()时,words是一个元组,包含元素的索引,然后是值。所以当你这样做的时候:

def print_table(width, data):
     #print(data)
     for words in enumerate(data):
         for word in enumerate(words):
             print(word)

你的行为不符合我的期望。你应该使用更传统的for循环。此外,您应该使用rjust来右对齐元素。
你的显示循环应该像这样:

def print_table(width, data):
     for i in range(len(data[0])):
         for j in range(len(data)):
             print(data[j][i].rjust(width[j]), end=' ')
         print()

EDIT注意range(len())被弃用,因为它会导致性能问题(每次迭代时,长度都会重新计算)而且,使用这种“for”循环不是很好的Python实践。参见:https://docs.python-guide.org/writing/style/#unpacking
您可以改用for index, value in enumerate(...),或者只计算一次大小

相关问题