简体   繁体   English

如何存储在Python中作为输出生成的数字列表?

[英]How to store a list of numbers generated as output in Python?

Suppose I want to add several numbers together like: 1. Find even numbers between 1-100. 假设我想将几个数字加在一起,例如:1.查找1-100之间的偶数。 2. Find odd numbers between 2-200. 2.查找2-200之间的奇数。 3. Add them. 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? 现在我该怎么做?

ie store the output of the first step, store the output of second step and then add them together. 例如,存储第一步的输出,存储第二步的输出,然后将它们加在一起。

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 这是有关此文档的链接: http : //docs.python.org/2/tutorial/datastructures.html#list-comprehensions

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)

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

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 清单记录在python docs上的http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

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

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

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