简体   繁体   English

如何使用列表理解将 append 字符串放入列表

[英]How to append string into list using list comprehension

Ex:前任:

a = []
a.append('Hello')

Which will give the output: ['Hello']这将给出 output: ['Hello']

Could you please tell me How to do the same using list comprehension?你能告诉我如何使用列表理解做同样的事情吗?

If you only have如果你只有

a = []
a.append('Hello')

as you know, it would be most practical to simply do如您所知,简单地做是最实用的

a = ['Hello']

But if you want to append multiple 'Hello' s to the list, you can do it like但是如果你想 append 多个'Hello'到列表中,你可以这样做

a = ['Hello' for _ in range(amount)]

Where the amount variable should be replaced with the number of 'Hello' s you want in the list.应将amount变量替换为列表中所需的'Hello'数量。

Another way to do the above is执行上述操作的另一种方法是

a = ['Hello'] * amount

You actually do not need to use list comprehension here.您实际上不需要在这里使用列表推导。 Just simply do:只需执行以下操作:

a=['Hello']

You can do it by doing你可以这样做

a = ['Hello' for i in range(1)]

But it will just lead to more memory allocation than needed.但这只会导致比需要更多的 memory 分配。

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

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