如何在 Python 中存储作为输出生成的数字列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14476134/
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
How to store a list of numbers generated as output in Python?
提问by Himanshu Arora
Suppose I want to add several numbers together like: 1. Find even numbers between 1-100. 2. Find odd numbers between 2-200. 3. Add them.
假设我想将几个数字相加,例如: 1. 找出 1-100 之间的偶数。2. 找出 2-200 之间的奇数。3. 添加它们。
So for this, I can check for even numbers and odd numbers respectively, but to add them, they must be stored somewhere. Now how can I do this?
所以为此,我可以分别检查偶数和奇数,但要添加它们,它们必须存储在某个地方。现在我该怎么做?
i.e. store the output of the first step, store the output of second step and then add them together.
即存储第一步的输出,存储第二步的输出,然后将它们相加。
采纳答案by TerryA
Find even numbers between 1-100:
查找 1-100 之间的偶数:
>>> l = [i for i in range(1,101) if i % 2 == 0]
>>> print l
[2, 4, 6, ..., 100]
Find odd numbers between 2-200:
找出 2-200 之间的奇数:
>>> l2 = [i for i in range(2,200) if i % 2 != 0]
>>> print l2
[3, 5, 7, ..., 199]
Find the sum:
求总和:
>>> total = sum(l) + sum(l2)
>>> print total
12540
What I've done is List Comprehensions, a loop which creates values for whatever factors you want. Here's a link to the documentation about it: http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
我所做的是 List Comprehensions,这是一个循环,可以为您想要的任何因素创建值。这是有关它的文档的链接:http: //docs.python.org/2/tutorial/datastructures.html#list-comprehensions
回答by Blender
This is what containers like lists are for:
这就是像列表这样的容器的用途:
numbers = [] # Setup an empty list
for number in range(10): # Loop over your numbers
numbers.append(number) # Append the number to your list
print sum(numbers) # 45
回答by Priya Ranjan Singh
Results of first and second steps can be stored in 2 different lists.
第一步和第二步的结果可以存储在 2 个不同的列表中。
list1 = [2, 4, 6 .. ]
list2 = [1, 3, 5 .. ]
Lists are documented on python docs at http://docs.python.org/2/tutorial/datastructures.html#more-on-lists
列表记录在http://docs.python.org/2/tutorial/datastructures.html#more-on-lists 的python 文档中
回答by nsconnector
Even Numbers List:
偶数列表:
a = [i for i in range(2,101,2)]
Odd Numbers List:
奇数列表:
b = [i for i in range(3,200,2)]
Sum:
和:
c = sum(a) + sum(b)
回答by Burhan Khalid
You don't really need a list.
你真的不需要清单。
>>> sum(x for x in range(1,100) if x % 2)
2500
>>> sum(x for x in range(2,200) if not x % 2)
9900

