首页 > 解决方案 > 有没有办法将字符串附加到第一个位置的每个列表?

问题描述

所以我遇到的问题是,我有一个列表(其中包含所有元素)并且我想将一个字符串(例如'watch')附加到列表中的每个元素但在第一个位置。

list = ['sample', 'test', 'hello']
string = 'watch '

# the result should like this:
# ['watch sample', 'watch test', 'watch hello']

我已经尝试过几次了。但是,它总是给出错误消息。有没有办法解决这个问题?谢谢你。

标签: pythonlistdata-structuresdataset

解决方案


l = ['sample', 'test', 'hello']
string = 'watch '

output = [string + i for i in l]

print(output)
>>> ['watch sample', 'watch test', 'watch hello']

请注意,我使用l而不是list. 一般来说,你不应该用这样的术语来重载。


推荐阅读