حلقات for المتداخلة
تعرف على حلقات "for" المتداخلة في Python، واستكشف بنيتها وحالات استخدامها وأمثلة عملية.
سنغطي ما يلي...
Python lets us easily create loops within loops. The inner loop will always complete before the outer loop. For each iteration of the outer loop, the iterator in the inner loop will complete its iterations for the given range, after which the outer loop can move to the next iteration.
Using a nested for
loop
Let’s take an example. Suppose we want to print two elements in a list whose sum is equal to a certain number n
.
The simplest way would be to compare every element with the rest of the list. A nested for
loop is perfect for this:
n = 50num_list = [10, 25, 4, 23, 6, 18, 27, 47]for n1 in num_list:for n2 in num_list: # Now we have two iteratorsif(n1 + n2 == n):print(n1, n2)
في الكود أعلاه، يُقارن كل عنصر مع كل عنصر آخر للتحقق مما إذا كان n1 + n2
يساوي n
. هذه هي قوة الحلقات المتداخلة. تعرض الشرائح أدناه قيمة كل متغير في كل تكرار.
كلمة المفتاح " break
أحيانًا، نحتاج إلى الخروج من الحلقة قبل وصولها إلى نهايتها. يحدث هذا إذا وجدنا ما نبحث عنه ولم نكن بحاجة إلى إجراء أي عمليات حسابية أخرى فيها.
مثال مثالي هو ما تناولناه للتو. عند نقطة معينة، ...