我有這個功能:
numbers = [3, 4, 6, 7]
for x in numbers:
a = 5 - x
b = 5 x
c = 5 * x
print(x, a, b, c)
它到底做什么并不重要,只有 x 是相關的。
我想修改 x 以便:
for x in numbers:
a = 5 - (x 2)
b = 5 (x 2)
c = 5 * (x 2)
print((x 2), a, b, c)
但顯然 2到處添加很煩人,所以我只想為x.
當然,我可以像這樣創建另一個變數:
for x in numbers:
modifiedX = x 2
a = 5 - modifiedX
b = 5 modifiedX
c = 5 * modifiedX
print(modifiedX, a, b, c)
但我很好奇是否可以在不添加另一行的情況下獲得相同的結果,例如:
for x 2 in numbers:
a = 5 - x
b = 5 x
c = 5 * x
print(x, a, b, c)
或這個:
x 2 for x in numbers:
a = 5 - x
b = 5 x
c = 5 * x
print(x, a, b, c)
最后 2 個代碼塊不是正確的 Python 語法,所以我很好奇:是否有正確的方法可以在x不添加更多行的情況下修改版本?
注意:我還是想保留原來的數字串列,所以我不是要直接改變串列中的數字。
uj5u.com熱心網友回復:
You can use map() to generate a new iterable that contains the elements of numbers incremented by 2. Since map() creates a new iterable, the original list isn't modified:
numbers = [3, 4, 6, 7]
for x in map(lambda x: x 2, numbers):
a = 5 - x
b = 5 x
c = 5 * x
print(x, a, b, c)
This outputs:
5 0 10 25
6 -1 11 30
8 -3 13 40
9 -4 14 45
uj5u.com熱心網友回復:
This also works if you want a short answer:
numbers = [3, 4, 6, 7]
[print(x, 5-x, 5 x, 5*x) for x in map(lambda x: x 2, numbers)]
Output:
5 0 10 25
6 -1 11 30
8 -3 13 40
9 -4 14 45
uj5u.com熱心網友回復:
list comprehension can work
for x in [y 2 for y in numbers]:
a = 5 - x
b = 5 x
c = 5 * x
print(x, a, b, c)
uj5u.com熱心網友回復:
The things being done to x can be wrapped into a function. This function will perform the series of actions being done to x and print the results.
def do_things(x):
a = 5 - x
b = 5 x
c = 5 * x
print(x, a, b, c)
Then you can loop through the defined values and call the function with x unchanged
numbers = [3, 4, 6, 7]
for x in numbers:
do_things(x)
3 2 8 15
4 1 9 20
6 -1 11 30
7 -2 12 35
Or you can modify the value of x as you call the function:
for x in numbers:
do_things(x 2)
5 0 10 25
6 -1 11 30
8 -3 13 40
9 -4 14 45
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/447417.html
