首页 > 解决方案 > 我正在尝试创建一个程序,将 2 个(用户)输入转换为列表,然后在列表中打印重复项

问题描述

出于某种原因,程序会打印重复项,但不是全部。例如,如果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')

标签: pythonpython-3.x

解决方案


您的初始逻辑不起作用,因为当它到达最后一个字符t时,它已经存在于duplicates列表中,因此if i not in duplicates:被评估为False最后一个t不添加到duplicates列表中

相反,对于您的重复逻辑,您应该检查一个字符 inx是否存在y,如果存在,请将其添加到duplicates列表中,您也不需要转换string为 alist而是可以直接迭代字符

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]

推荐阅读