In Python, lambdas are anonymous functions, and when you print them directly, you see their representation rather than their values. To get the actual values, you need to call these lambda functions with arguments. Here’s how you can modify your code to achieve this:
pythonmult = [lambda x, i=i: x*i for i in range(4)]
for v in mult:
print(v(5)) # Call the lambda with an argument (e.g., 5) to get the result
This will output:
0 5 10 15
Each value in the output corresponds to the result of calling the lambda function with the argument 5
.
المزيد من المعلومات
في هذا الكود، تقوم بإنشاء قائمة mult
تحتوي على 4 دوال لامبدا. كل دالة لامبدا تأخذ عددًا x
وتضربه في i
، حيث يتغير i
من 0 إلى 3 بفضل range(4)
.
عندما تقوم بطباعة الدوال لامبدا داخل الحلقة، فإنك ترى تمثيلها النصي
وهو يعكس موقع الدالة في الذاكرة. لكي تحصل على القيم الفعلية للدوال، يجب عليك استدعاء الدوال بواسطة إعطاءها قيمة للمتغير x
.
في هذه الحالة، عندما تقوم بإرسال القيمة 5
كمعامل إلى الدوال، ستحصل على النتائج التالية:
0
: 0 * 55
: 1 * 510
: 2 * 515
: 3 * 5