[英]Make list with while loop ? python3
我试图使用while循环使列表包含(偶数个):
a=0
while a<8:
a=a+2
print(a,end=' ')
t=list(a)
print (t)
以及如何使代码将第一个列表中的数字分为两个列表:一个用于(偶数)而另一个用于(奇数)?
您可以直接从每个变量创建list
>>> a = list(a)
>>> a
[1, 2, 3]
>>> b = list(b)
>>> b
['C', 'i', 't', 'y']
要使用while
循环列出偶数列表,您可以执行以下操作
a = 0
t = []
while a < 8:
t.append(a)
a += 2
>>> print(t)
[0, 2, 4, 6]
请注意,以上只是出于学习目的,可以使用Python的range
函数更轻松地完成此操作
>>> list(range(0, 8, 2)) # Evens
[0, 2, 4, 6]
>>> list(range(1, 8, 2)) # Odds
[1, 3, 5, 7]
使用list
进行转换。
In [1]: a=(1,2,3)
In [2]: list(a)
Out[2]: [1, 2, 3]
In [3]: b=('City')
In [4]: list(b)
Out[4]: ['C', 'i', 't', 'y']
这是我对您问题的回答:
List = []
ListEven = []
ListOdd = []
Count = 0
while(Count < 11):
print(Count, end = ' ')
List.append(Count)
if(Count % 2 == 0):
ListEven.append(Count)
elif(Count % 2 != 0):
ListOdd.append(Count)
Count += 1
print("\n""This is the main list:")
print(List)
print("This is the even list:")
print(ListEven)
print("This is the odd list:")
print(ListOdd)
我将Count从Count += 2
固定为Count += 1
因为您要求提供list of odds
。 您拥有的代码only produce even numbers
。 我希望这有助于回答您的问题。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.