简体   繁体   English

如何向列表中的每个项目添加文本

[英]How do I add text to each item in a list

I want to add text to each item in a list and then it back into the list. 我想在列表中的每个项目中添加文本,然后将其重新添加到列表中。

Example

foods = [pie,apple,bread]
phrase = ('I like')
statement = [(phrase) + (foods) for phrase in foods]

I want to have the output (I like pie, I like apple, I like bread) 我想要输出(我喜欢馅饼,我喜欢苹果,我喜欢面包)

It prints out something along the lines of (hI like,pI like,pI like) 它打印出的东西(hI like,pI like,pI like)

You should avoid declaring phrase on another line, here is the sample that should make it. 你应该避免在另一行上声明短语,这是应该制作它的样本。

statement = ['I like ' + food for food in foods]  # Note the white space after I like

In your code you probably coded it too quickly because you are reasigning the value of phrase with the for phrase in foods . 在您的代码中,您可能编写的代码太快,因为您正在重新分配短语的值与for phrase in foodsfor phrase in foods Also when you do phrase + foods foods is a list which cannot be concatenated with string 此外,当你做phrase + foods食品是一个不能与字符串连接的列表

I prefer string formatting: 我更喜欢字符串格式:

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]

You can also create a container and use .format : 您还可以创建容器并使用.format

phrase = 'I like {}'
statement = [phrase.format(food) for food in ("pie","apple","bread")]
foods = ['pie','apple','bread']

phrase = 'I like'

statement = [phrase + ' ' + j for j in foods]

>>> statement
['I like pie', 'I like apple', 'I like bread']

The problem in your code was that you were using the iterator incorrectly. 您的代码中的问题是您错误地使用了迭代器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM