Python 多次将相同的值附加到列表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20426313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append the same value multiple times to a list
提问by Bsje
To make my program more beautiful instead of ugly, I am trying to find a more pythonic way of adding a single value multiple times to a list. I now use a loop, but I create a variable I do not use.
为了让我的程序更漂亮而不是丑陋,我试图找到一种更 Pythonic 的方式,将单个值多次添加到列表中。我现在使用一个循环,但我创建了一个我不使用的变量。
l = []; n = 5; v = 0.5
for i in xrange(n):
l.append(v)
Any ideas?
有任何想法吗?
采纳答案by Boo
To add v, n times, to l:
将 v、n 次添加到 l:
l += n * [v]
回答by Nils Werner
Try using list.extendand the multiply operator for lists
尝试list.extend对列表使用乘法运算符
l.extend([v] * n)
回答by JoeC
Try this
尝试这个
n = 5
v = 0.5
l = [v]*n
回答by Gareth Latty
The most general answer to this is to use list.extend()and a generator expression:
对此最普遍的答案是使用list.extend()和生成器表达式:
l.extend(generate_value() for _ in range(n))
This will add a value ntimes. Note that this will evaluate generate_value()each time, side-stepping issues with mutable values that other answers may have:
这将添加一个值n倍。请注意,这将generate_value()每次评估其他答案可能具有的可变值的问题:
>>> [[1]] * 5
[[1], [1], [1], [1], [1]]
>>> _[0].append(1)
>>> _
[[1, 1], [1, 1], [1, 1], [1, 1], [1, 1]]
>>> [[1] for _ in range(5)]
[[1], [1], [1], [1], [1]]
>>> _[0].append(1)
>>> _
[[1, 1], [1], [1], [1], [1]]
When using the multiplication method, you end up with a list of n references to the same list. When you change it, you see the change in every element of the list - as they are all the same.
使用乘法方法时,您最终会得到一个包含对同一列表的 n 个引用的列表。当您更改它时,您会看到列表中每个元素的更改 - 因为它们都是相同的。
When using a generator expression or list comprehension, a new list is created for each sub-item, so each item is a different value. Modifying one only affects that one.
使用生成器表达式或列表推导式时,会为每个子项创建一个新列表,因此每个项都是不同的值。修改一个只会影响那个。
Obviously, in your example, the values are immutable, so this doesn't matter - but it's worth remembering for different cases, or if the values might notbe immutable.
显然,在您的示例中,值是不可变的,所以这无关紧要 - 但对于不同的情况,或者值可能不是不可变的,值得记住。

