gpt4 book ai didi

python - 将相同的字符串添加到列表中的所有项目

转载 作者:IT老高 更新时间:2023-10-28 20:57:41 26 4
gpt4 key购买 nike

已通过 Stack Exchange 对已回答的问题进行了一些搜索,但无法找到我要查找的内容。

给定以下列表:

a = [1, 2, 3, 4]

我将如何创建:

a = ['hello1', 'hello2', 'hello3', 'hello4']

谢谢!

最佳答案

使用 list comprehension :

[f'hello{i}' for i in a]

列表推导式可让您将表达式应用于序列中的每个元素。这里的表达式是 formatted string literal ,将 i 合并到以 hello 开头的字符串中。

演示:

>>> a = [1,2,3,4]
>>> [f'hello{i}' for i in a]
['hello1', 'hello2', 'hello3', 'hello4']

关于python - 将相同的字符串添加到列表中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13331419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com