社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python-Modify for循环变量

JoJ3o • 3 年前 • 1153 次点击  

我得到了这个函数:

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)

最后两个代码块都不是正确的Python语法,所以我很好奇: 有没有正确的方法可以在不增加更多行的情况下修改x版本?

注意:我仍然想保留原来的数字列表,所以我不想直接更改列表中的数字。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129377
 
1153 次点击  
文章 [ 4 ]  |  最新文章 3 年前
Richard Dodson
Reply   •   1 楼
Richard Dodson    3 年前

正在做的事情 x 可以包装成一个函数。此函数将执行对x执行的一系列操作,并打印结果。

def do_things(x):
    a = 5 - x
    b = 5 + x
    c = 5 * x
    print(x, a, b, c)

然后可以循环使用定义的值,并在x不变的情况下调用函数

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

也可以在调用函数时修改x的值:

for x in numbers:
    do_things(x+2)

5 0 10 25
6 -1 11 30
8 -3 13 40
9 -4 14 45
necaris15
Reply   •   2 楼
necaris15    3 年前

清单理解可以奏效

for x in [y+2 for y in numbers]:
    a = 5 - x
    b = 5 + x
    c = 5 * x
    print(x, a, b, c)
catasaurus
Reply   •   3 楼
catasaurus    3 年前

如果你想要一个简短的答案,这也很有效:

numbers = [3, 4, 6, 7]
[print(x, 5-x, 5+x, 5*x) for x in map(lambda x: x + 2, numbers)]

输出:

5 0 10 25
6 -1 11 30
8 -3 13 40
9 -4 14 45
BrokenBenchmark
Reply   •   4 楼
BrokenBenchmark    3 年前

你可以用 map() 生成一个包含 numbers 增加2。自从 地图() 创建一个新的iterable,但不修改原始列表:

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)

这将产生:

5 0 10 25
6 -1 11 30
8 -3 13 40
9 -4 14 45