如果列表初始化为空白列表,为什么列表不为空? (蟒蛇)

时间:2018-05-30 05:24:52

标签: python

从此链接跟进: How do i store the output of the 'count' variable into a list? (python)

这是我的代码:

def printTable(items):
    counter_list = []
    for i in  range (len(items[0])):
        print ()
        counter = 0
        for j in range(len(items)):
            if len(items[i][j]) > counter:
                counter = len(items[i][j])
                counter_list.append(counter)
                itemName = items[i][j]
        print ('the longest string is: ' + itemName + '; and its length is ' + str(counter))
        print ('Counter list: ' + str(counter_list))

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


printTable(tableData)

这个输出是:

the longest string is: cherries; and its length is 8
Counter list: [6, 7, 8]

the longest string is: Alice; and its length is 5
Counter list: [6, 7, 8, 5]

the longest string is: moose; and its length is 5
Counter list: [6, 7, 8, 5, 4, 5]

Traceback (most recent call last):
  File "/Users/Inder/Documents/printTable.py", line 19, in <module>
    printTable(tableData)
  File "/Users/Inder/Documents/printTable.py", line 7, in printTable
    if len(items[i][j]) > counter:
IndexError: list index out of range

1 个答案:

答案 0 :(得分:0)

如果项目的长度超过前一项,则将每个项目附加到<GridView x:Name="GridView1" ItemContainerStyle="{StaticResource testGrid}" ItemsSource="{x:Bind testValue}" Width="1740" Height="835" IsHitTestVisible="False" ScrollViewer.HorizontalScrollBarVisibility="Hidden" Margin="75,190,75,100" FontFamily="Segoe MDL2 Assets" IsDoubleTapEnabled="False" IsHoldingEnabled="False" IsRightTapEnabled="False" IsTapEnabled="False"> <GridView.ItemTemplate> <DataTemplate x:DataType="data:Room"> <local:TemplateGrid x:Name="TemplateGridControl"/> </DataTemplate> </GridView.ItemTemplate> </GridView>

而不是 - 只追加行中最长的项目:

counter_list

另外:代替def printTable(items): counter_list = [] for i in range (len(items[0])): print () counter = 0 for j in range(len(items)): if len(items[i][j]) > counter: counter = len(items[i][j]) itemName = items[i][j] counter_list.append(counter) print ('the longest string is: ' + itemName + '; and its length is ' + str(counter)) print ('Counter list: ' + str(counter_list)) 查看enumerate

实际上根本不需要使用项目索引。 这是稍微重构的版本:

range(len(items))

您可能还想看一下精彩的Counter模块:

def printTable(items):
    counter_list = []
    for row in items:
        longest_item, longest_len = '', 0
        for item in row:
            if len(item) > longest_len:
                longest_item, longest_len = item, len(item)
        counter_list.append(longest_len)
        print (f'the longest string is: {longest_item}; and its length is {longest_len}')
        print ('Counter list: ' + str(counter_list))