【发布时间】:2020-09-07 20:58:07
【问题描述】:
我正在学习 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
所以,当他说 while y 我不明白为什么 len(third) 是 1 而不是 0,因为 third 在 while 部分之前设置为空。有什么我遗漏的吗?
谢谢。
【问题讨论】:
-
third以空列表(未设置)开始,但在外部循环的迭代过程中填充 -
顺便说一句,这真的不是pythonic代码
-
友情建议:找一本新书。快的!去。现在。
-
我建议不要使用用户输入代码让您的生活变得艰难,而是使用几个预定义的列表进行开发和测试,例如
first = [1, 2, 3]。 (顺便说一句,您的问题被标记为python,无需在标题中添加[PYTHON]) - 在第一次迭代中,该循环被跳过,但一旦将内容添加到third,它就可以运行。 -
正如@Chris_Rands 所说,这不是 Pythonic 代码,并且正如 S3DEV 所建议的那样,我鼓励您寻找其他资源来学习
标签: python python-3.x list