当你看到变量' count'初始值为0.这会在循环运行时被另一个值覆盖;我们可以说新值是' 8'。然后当循环再次运行时,新值为' 8'被新的价值所覆盖;我们可以说新值是' 5'。这意味着价值' 8'是不可恢复的。我不想丢失从循环中创建的任何值,而是将它们存储到列表中。如何将创建的值存储到列表中?
这是我的代码:
def printTable(items):
for i in range (len(items[0])):
print ()
counter = 0
for j in range(len(items)):
if len(items[i][j]) > counter: count = len(items[i][j])
itemName = items[i][j]
print ('the longest string is: ' + itemName + '; and its length is ' + str(counter))
tableData = [['apples','oranges','cherries','banana'],
['Alice','Bob','Carol','David'],
['dogs','cats','moose','goose']]
printTable(tableData)
答案 0 :(得分:1)
创建一个列表,然后在每次循环运行时将count的值附加到它。
def printTable(items):
count_list = []
for i in range (len(items[0])):
print ()
counter = 0
for j in range(len(items)):
if len(items[i][j]) > counter:
count = len(items[i][j])
count_list.append(count)
itemName = items[i][j]
print ('the longest string is: ' + itemName + '; and its length is ' + str(counter))
return count_list
tableData = [['apples','oranges','cherries','banana'],
['Alice','Bob','Carol','David'],
['dogs','cats','moose','goose']]
printTable(tableData)