如何在Python for循环中就地转换值?

0 投票
2 回答
545 浏览
提问于 2025-06-08 05:48

在这个简单的Python例子中:

arr = [1,2,3,4,5]
for n in arr: 
    s = str(n)
    print(s) 

我想写的代码有点像 [str(n) for n in arr],但格式要改成下面这样:

arr = [1,2,3,4,5]
for str(n) as s in arr: 
    print(s) 

我基本上想在 for 循环里面加上 s=str(s)。有没有什么简单的方法可以在Python中做到这一点?

相关问题:

  • 暂无相关问题
暂无标签

2 个回答

1

你根本不需要使用 str。其实,print 函数会自动把你传给它的内容转换成字符串。

所以你可以直接这样写:

for n in arr:
    print(n)

无论 n 是什么类型。

参考链接:https://docs.python.org/3/library/functions.html#print

1

这里有至少两种方法:

map:

arr = [1,2,3,4,5]
for s in map(str, arr): 
    print(s)

生成器推导式:

arr = [1,2,3,4,5]
for s in (str(n) for n in arr):
    print(s) 

撰写回答