python - 我正在尝试创建一个程序,将 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')
解决方案
您的初始逻辑不起作用,因为当它到达最后一个字符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]
推荐阅读
- android - 回收器视图中的回收器视图垂直滚动不起作用
- html - 首先如何让 Bootstrap Collapse 隐藏内容?
- python - ImportError:无法从“tensorflow”导入名称“set_random_seed”(C:\Users\polon\Anaconda3\lib\site-packages\tensorflow\__init__.py)
- javascript - 单击视频后,我想在模型对话框中显示视频
- unit-testing - TypeError: moment 不是函数 - Angularjs Jasmine 测试用例
- javascript - 更改类属性
- java - Alphavantage.co :无法以 5 分钟间隔获取历史数据
- javascript - 测试失败 - 多次调用 Mocha 的 done()
- laravel - 在 Laravel Model 类上添加自定义方法以在另一个表中插入记录是一种好习惯吗?
- neo4j - CQL 语法异常