试图理解列表的长度[PYTHON]

2024-04-25 23:56:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python,目前我的重点是列表。 我正在读的这本书将此代码用作创建第三个列表的示例,它不会重复两个列表中存在的元素:

first = []
second = []
while True:
    e = int(input("Enter a value for the first list (0 to end):")) 
    if e==0:
        break
    first.append(e)
while True:
    e = int(input("Enter a value for the second list (0 to finish):")) 
    if e==0:
        break
    second.append(e)
third = []

two_lists = first[:]
two_lists.extend(second)
x=0
while x < len(two_lists):
    y = 0
    while y < len(third): #**THIS LINE IS MY QUESTION**
        if two_lists[x] == third[y]:
            break;
        y=y+1
    if y == len(third):
        third.append(two_lists[x])
    x=x+1
x=0
while x < len(third):
    print(third[x])
    x=x+1

所以,当他说;len(third)我不明白为什么len(third)是1而不是0,因为third在while部分之前设置为空。有什么我不知道的吗

谢谢


Tags: true列表inputleniflistsintfirst
3条回答

在第18行循环的第一次迭代中,len(third)实际上是0不是1

所以我们没有进入第20行的while循环,而是进入第24行的if子句,只有len(third)上的那部分才是正的

初始迭代的第三个循环的长度应该是0,这样整个while循环都将被跳转。 然后,以下if语句将测试true,因为0等于0,然后将向第三个数组中添加一个元素

这是真的,第一次来到这个while循环

但是,外部循环填充第三个列表

相关问题 更多 >