我想向列表中的每个项目添加文本,然后将其重新添加到列表中。
示例
foods = [pie,apple,bread]
phrase = ('I like')
statement = [(phrase) + (foods) for phrase in foods]
我想要输出(我喜欢馅饼,我喜欢苹果,我喜欢面包)
它按照(hI like,pI like,pI like)的内容打印出一些东西
答案 0 :(得分:2)
您应该避免在另一行上声明短语,这是应该使用的示例。
statement = ['I like ' + food for food in foods] # Note the white space after I like
在您的代码中,您可能编码得太快,因为您要用for phrase in foods
重新分配短语的值。同样,当您做phrase + foods
食物时,该列表也不能与字符串连接
答案 1 :(得分:1)
我更喜欢字符串格式:
foods = ['pie','apple','bread']
phrase = 'I like'
statement = ['{0} {1}'.format(phrase, j) for j in foods]
# Python 3.6+
statement = [f'{phrase} {j}' for j in foods]
答案 2 :(得分:0)
您还可以创建一个容器并使用.format
:
phrase = 'I like {}'
statement = [phrase.format(food) for food in ("pie","apple","bread")]
答案 3 :(得分:0)
foods = ['pie','apple','bread']
phrase = 'I like'
statement = [phrase + ' ' + j for j in foods]
>>> statement
['I like pie', 'I like apple', 'I like bread']
代码中的问题是您使用的迭代器不正确。