python列表和要附加到列表的for循环
我试图创建另一个空列表newlist=[],并编写第二个for循环,检查列表中的每个元素是否为偶数,如果为偶数,则将该元素追加到newlist。 这是到目前为止我的代码python列表和要附加到列表的for循环,python,for-loop,Python,For Loop,我试图创建另一个空列表newlist=[],并编写第二个for循环,检查列表中的每个元素是否为偶数,如果为偶数,则将该元素追加到newlist。 这是到目前为止我的代码 list = [] for item in range(5): next = int(input("Please enter an integer value: ")) list.append(next) print list 你可以这么做 newlist = [i for i in mylist if i%2
list = []
for item in range(5):
next = int(input("Please enter an integer value: "))
list.append(next)
print list
你可以这么做
newlist = [i for i in mylist if i%2 == 0]
不要命名变量列表,它已经是内置函数的名称
从代码中可以看出,追加似乎不在for循环的范围内发生。相反,您希望:
for item in range(5):
next = int(input("Please enter an integer value: "))
mylist.append(next) # indented!
然后,您可以通过上面显示的内容获得偶数值。您可以使用一个简单的for循环:
不要将变量称为任何保留字,我知道您可能只是将它们命名为示例,但如果您是,请重命名列表和下一步您是否可以提供示例输入和输出,如果需要,为什么前者导致后者,而不是有点混乱的描述和用户输入代码?你不应该使用列表作为变量名!
lst = []
for item in range(5):
next = int(input("Please enter an integer value: "))
lst.append(next)
print lst
secondlist = []
for item in list:
if item % 2 == 0: # check if item is even
secondlist.append(item)
nextlist = []
for i in list:
if i % 2 == 0: nextlist.append(i)
print nextlist