使用while循环列出列表?蟒蛇3



我正在尝试使用while循环使列表包含(偶数):

a=0
while a<8:
    a=a+2
    print(a,end=' ')
    t=list(a)
    print (t)

我如何制作一个代码,将第一个列表中的数字划分为两个列表:一个用于(偶数),另一个用作(奇数)?

使用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

>>> 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 = []
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。我希望这有助于回答你的问题

最新更新