由于某种原因,程序会打印重复项,但不会打印全部。例如,如果list1 = 'test'
和list2 = 'test'
它打印['t','e','s']
dublicates = []
x = input('type something : ')
y = input('type something again : ')
list1 = list(x)
list2 = list(y)
for i in list2:
if i not in dublicates:
dublicates.append(i)
print (dublicates)
end = input('press enter to exit')
您的初始逻辑不起作用,因为当到达最后一个字符时t
,它已经存在于duplicates
列表中,因此if i not in duplicates:
被评估为False
并且最后一个t
未添加到duplicates
列表中
相反,你重复的逻辑,你应该检查是否在一个字符x
出现在y
与否,如果存在,将其添加到duplicates
列表中,你也并不需要转换string
到一个list
比较,你可以对人物直接迭代
duplicates = []
x = input('type something : ')
y = input('type something again : ')
#Iterate through x
for i in x:
#For every character in x, check if it present in y
if i in y:
duplicates.append(i)
print(duplicates)
end = input('press enter to exit')
输出将是
type something : test
type something again : test
['t', 'e', 's', 't']
press enter to exit
获取重复项的类似列表理解方法是
duplicates = [ i for i in x if i in y]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句