Sss123057057 发表于 2021-2-19 17:05:13

for

1.当for后面接的是列表时,程序是怎样运行的?
shoplist = ['apple', 'mango', 'carrot', 'banana']

print('I have', len(shoplist), 'items to purchase.')

print('These items are:', end=' ')
for item in shoplist:
    print(item, end=' ')

2.当for后面接的是字典的键值对时,一定需要两个变量吗?
allguess={'1':{'apples':5,'pretzeles':12},
         '2':{'ham sandwiches':3,'apples':2},
         '3':{'cups':3,'apple pies':1}}
def a(guests,item):
    numbrount=0
    for k,v in guests.items():
      numbrount=numbrount+v.get(item,0)

考不好不改名 发表于 2021-2-19 17:52:07

1.接列表时,是这样运行的:
依次从列表的第零个元素起直到最后一个元素分别赋值给变量,执行一次代码

2.接字典且变量只用一个时,变量迭代字典的键,如:di = {1:'one', 2:'two', 3:'three'}
for key in di:
    print(key, di)
页: [1]
查看完整版本: for