Python:在没有 for 循环的情况下将值附加到列表 [英] Python: Append values to list without for-loop
本文介绍了Python:在没有 for 循环的情况下将值附加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不使用 for 循环的情况下将值附加到列表中?
我想避免在这段代码中使用循环:
count = []对于范围内的 i (0, 6):打印将 %d 添加到列表中."% 一世count.append(i)
结果必须是:
count = [0, 1, 2, 3, 4, 5]
我尝试了不同的方法,但我无法做到.
解决方案
范围:
因为 range
返回一个列表,你可以简单地做
避免循环的其他方法(docs):
扩展:
<预><代码>>>>计数 = [1,2,3]>>>count.extend([4,5,6])>>>数数[1, 2, 3, 4, 5, 6]相当于count[len(count):len(count)] = [4,5,6]
,
和功能与count += [4,5,6]
相同.
切片:
<预><代码>>>>计数 = [1,2,3,4,5,6]>>>计数[2:3] = [7,8,9,10,11,12]>>>数数[1, 2, 7, 8, 9, 10, 11, 12, 4, 5, 6](从 2 到 3 的 count
切片被右边的可迭代内容替换)
How can I append values to a list without using the for-loop?
I want to avoid using the loop in this fragment of code:
count = []
for i in range(0, 6):
print "Adding %d to the list." % i
count.append(i)
The result must be:
count = [0, 1, 2, 3, 4, 5]
I tried different ways, but I can't manage to do it.
解决方案
Range:
since range
returns a list you can simply do
>>> count = range(0,6)
>>> count
[0, 1, 2, 3, 4, 5]
Other ways to avoid loops (docs):
Extend:
>>> count = [1,2,3]
>>> count.extend([4,5,6])
>>> count
[1, 2, 3, 4, 5, 6]
Which is equivalent to count[len(count):len(count)] = [4,5,6]
,
and functionally the same as count += [4,5,6]
.
Slice:
>>> count = [1,2,3,4,5,6]
>>> count[2:3] = [7,8,9,10,11,12]
>>> count
[1, 2, 7, 8, 9, 10, 11, 12, 4, 5, 6]
(slice of count
from 2 to 3 is replaced by the contents of the iterable to the right)
这篇关于Python:在没有 for 循环的情况下将值附加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文