To create a function that can handle a dynamic number of nested loops, you can use recursion. Here’s an example of how you can define such a function in Python:
pythondef dynamic_nested_loops(arrays, current_loop=0, current_values=[]):
if current_loop == len(arrays):
print(*current_values)
return
for value in arrays[current_loop]:
dynamic_nested_loops(arrays, current_loop + 1, current_values + [value])
# Example usage
a = [1]
b = [2, 3]
c = [4, 5, 6]
d = [a, b, c]
dynamic_nested_loops(d)
This function takes a list of arrays (arrays
) and a current loop index (current_loop
). It recursively loops over each array, appending the current value to a list (current_values
) and calling itself with the next array and updated values until it reaches the end, at which point it prints the values.
المزيد من المعلومات
تستخدم الدالة dynamic_nested_loops
في الكود السابق الإعادة التشعبية لإنشاء عدد ديناميكي من الحلقات التداخلية. تأخذ الدالة قائمة من المصفوفات (arrays
) وفهرس الحلقة الحالي (current_loop
). تكرر الدالة بشكل تكراري على كل مصفوفة، ملتصقة القيمة الحالية بقائمة (current_values
) وتستدعي نفسها بمصفوفة القادمة والقيم المحدثة حتى تصل إلى النهاية، حيث تقوم بطباعة القيم.
تستخدم الدالة dynamic_nested_loops
الطباعة بشكل مستقيم print(*current_values)
لطباعة القيم بدون أي فواصل بينها. وتستخدم المعاملات الافتراضية في الدالة لتمرير قيم مبدئية للمتغيرات current_loop
و current_values
في أول مرة يتم فيها استدعاء الدالة.
يمكنك تغيير قائمة d
لتتناسب مع عدد الحلقات التي ترغب في تكرارها.