亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Python 中創建一個包含兩個變量的循環,其中一個變量僅在每第 n 次循環后發生變化

在 Python 中創建一個包含兩個變量的循環,其中一個變量僅在每第 n 次循環后發生變化

幕布斯7119047 2023-06-06 15:04:27
我正在嘗試編寫一個程序,其中有兩個列表和一個字典:dict = {'fruit1' : 'apple', 'fruit2' :'banana', 'fruit3':'cherry' ....and so on} list1 = ['a','b','c','d','e'....]list2 = ['fruit1', 'fruit2','fruit3'....]我有一個看起來像這樣的程序。[這根本不對,但它有助于代表我想要得到的結果]。for obj1 in list1:    for obj_2 in list2:        print(obj1)        print(obj_2)        print(dict[obj_2])我的需要是以每第n個循環改變一次obj_2但obj_1改變每個循環的方式循環它。我怎樣才能做到這一點?所以我的結果看起來像(考慮第 n 個循環是第 3 個循環):afruit1applebfruit1applecfruit1appledfruit2bananaefruit2bananaffruit2bananagfruit3cherry...
查看完整描述

2 回答

?
慕田峪9158850

TA貢獻1794條經驗 獲得超8個贊

使用計數器變量而不是嵌套循環。每次通過循環增加計數器,當它到達時n將其包裝回0并將索引增加到list2.


n = 3

list2_index = 0

counter = 0

for obj1 in list1:

    obj_2 = list2[list2_index]

    print(obj1)

    print(obj_2)

    print(dict[obj_2])

    counter += 1

    if counter == n:

        counter = 0

        list2_index += 1

順便說一句,不要用作dict變量名,它是內置類型的名稱。


查看完整回答
反對 回復 2023-06-06
?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

因此,您要做的就是更改兩個 for 循環的位置。


#BTW it isn't adviced to use reserved keywords for variable names so dont use Dict for a variable name

myDict = {'fruit1' : 'apple', 'fruit2' :'banana', 'fruit3':'cherry'}?

list1 = ['a','b','c','d','e']

list2 = ['fruit1', 'fruit2','fruit3']


#so in this nested loop obj2 only changs after? the n loops (n being the length of list1)

#which is after list1 is complete and it does that over and over?

#until list2 is complete

for obj2 in list2:

? ? for obj1 in list1:

? ? ? ? print(obj1)

? ? ? ? print(obj2)

? ? ? ? print(myDict[obj2])

如果這就是您的意思,那么這里是另一段代碼。


myDict = {'fruit1' : 'apple', 'fruit2' :'banana', 'fruit3':'cherry'}?

list1 = ['a','b','c','d','e']

list2 = ['fruit1', 'fruit2','fruit3']


#a variable to keep track of the nth loop

nthLoop = 1?

for obj2 in list2:

? ? for obj1 in list1:

? ? ? ? #if you print for three times which is what you wanted for your nthloop to be?

? ? ? ? #then break, which will break out of this nested loop allowing to only print 3 times and also set the?

? ? ? ? #nthLoop back to zero so that it will work nicely for the next iteration

? ? ? ? if nthLoop > 3:

? ? ? ? ? ? nthLoop = 0

? ? ? ? ? ? break

? ? ? ? print(obj1)

? ? ? ? print(obj2)

? ? ? ? print(myDict[obj2])

? ? ? ? nthLoop += 1


查看完整回答
反對 回復 2023-06-06
  • 2 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號