[英]How to print list of even numbers using Python
I'm trying to write a python program that will prompt the user for an integer greater than 1 and reads those integers into a list followed by producing two lists and returning those values. 我正在尝试编写一个python程序,该程序将提示用户输入大于1的整数并将这些整数读入列表,然后生成两个列表并返回这些值。 Where should I start? 我应该从哪里开始?
A list titled "listOfNumbers" has been created. 已创建一个名为“ listOfNumbers”的列表。 I need to produce a new list that only contains integers from listOfNumbers that have even induces in listOfNumbers. 我需要产生一个仅包含listOfNumbers中的整数(甚至在listOfNumbers中引入)的新列表。
def make_a_list(*listOfNumbers):
for x in numList:
if x % 2 == 0:
print x
listOfNumbers.append(x)
print(make_a_list(4, 5, 6, 7, 9, 11, 10, -12, -18, 1, 0)
I excepted a list that has the user type in a series of numbers but I'm not sure how this will turn out. 我排除了一个列表,该列表具有一系列数字的用户类型,但是我不确定结果如何。
As @geckos pointed out you can just use indexing to specify this range. 正如@geckos指出的那样,您可以仅使用索引来指定此范围。 Supposing we have: 假设我们有:
my_list = [4, 5, 6, 7, 9, 11, 10, -12, -18, 1, 0]
And we want evens using a counting scheme of [1, 2, 3, 4, 5, ...]
, then we would call: 我们想要使用[1, 2, 3, 4, 5, ...]
的计数方案来偶数,那么我们将调用:
print(my_list[1::2])
Outputting: 输出:
[5, 7, 11, -12, 1]
This is because you specify the index as [start:stop:step size]
but normally the step size is omitted, and therefore defaults to 1. 这是因为您将索引指定为[start:stop:step size]
但通常会忽略步长,因此默认为1。
If instead you mean a counting scheme of [0, 1, 2, 3, 4, 5, ...]
then just adjust the index to [::2]
相反,如果您指的是[0, 1, 2, 3, 4, 5, ...]
的计数方案,则只需将索引调整为[::2]
Note you can also use negative step sizes. 请注意,您也可以使用负步长。 For instance: 例如:
print(my_list[::-1])
Outputs the list in reverse order, or: 以相反的顺序输出列表,或者:
[0, 1, -18, -12, 10, 11, 9, 7, 6, 5, 4]
To put it into a function would look like: 将其放入一个函数看起来像:
def make_a_list(input_list):
even_index_list = input_list[1::2]
return even_index_list
this will give you the list of all even numbers 这将为您提供所有偶数的列表
def make_a_list(*listOfNumbers):
even_list =[]
for num in listOfNumbers:
if num%2==0:
even_list.append(num)
return even_list
print(make_a_list(4, 5, 6, 7, 9, 11, 10, -12, -18, 1, 0))
# output [4, 6, 10, -12, -18, 0]
this will give you numbers at even indices 这将为您提供偶数索引的数字
def even_indices(*listOfNumbers):
return listOfNumbers[2::2]
print(even_indices(4, 5, 6, 7, 9, 11, 10, -12, -18, 1, 0))
# output (6, 9, 10, -18, 0)
Use range() to increment by two while looping. 循环时使用range()增加2。
def make_a_list(*listOfNumbers):
output_list = []
for i in range(0, len(listOfNumbers), 2):
output_list.append(listOfNumbers[i])
return output_list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.