As you see that the variable 'count' has an initial value of 0. This get overwritten by the another value when the loop is ran; lets say the new value is '8'. Then as the loop runs again the new value of '8' get overwritten by the newer value; lets say the new value is '5'. This means that value '8' is unrecoverable. I do not want to lose any of the values being created from the loop, but rather store them into list. How do i store the created values into a list?
Here is my code:
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)
Make a list, and then append the value of count to it every run of the loop.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.