在一个lin中创建n个空字符串

2024-05-13 21:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

可能是重复的(对不起)。我环顾四周,找不到答案。

我想在一行中生成一个空字符串列表。

我试过:

>>> list(str('') * 16)
# ['']
>>> list(str(' ') * 16)
# [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
# anything with a char in it is working

下面的方法行得通,但是有更好的方法吗?为什么list(str('') * 16)不起作用?

>>> [str() for c in 'c' * 16]
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

Tags: 方法字符串答案in列表foriswith
2条回答

你可以把这样的单子乘出来。因为''是不可变的,所以不必担心它们都是对同一字符串的引用。

[''] * 16

不能对可变对象(如列表或听写)使用相同的技巧。你需要用上一个版本

[mutable_thing() for c in range(16)]

或者

[[] for c in range(16)]

或者

[{} for c in range(16)]

请参见Python standard types page

>>> [''] * 16
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

s * n, n * s

n shallow copies of s concatenated

其中,s是一个序列,n是一个整数。

此操作文档的完整脚注:

Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; consider:

>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]

What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are (pointers to) this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]

相关问题 更多 >