python-3.x - python:显示列表中的唯一元素
问题描述
我是这种 python 语言的新手:我在以下 pgm 中显示列表中的唯一元素时遇到问题:以下是我的程序:
def unique_list(lst):
c = []
for i in lst:
if (lst.count(i)>=1) & i not in c:
c.append(i)
#print(c)
return c
print(unique_list([1,1,1,2,2,3,3,4,5]))
我收到的输出为:
[1,2,2,4]
代替[1,2,3,4,5]
我认为 if stmt 中有一个错误……谁能解释一下我得到这个输出了吗?
解决方案
您可以通过将列表转换为集合来获取列表中的唯一元素:
print(set([1,1,1,2,2,3,3,4,5]))
推荐阅读
- asp.net - 如何在 WebForm ASP.Net 中模拟 MVC 路由?
- r - 使用正则表达式在 R 中提取数据
- python - 使用 Beautiful Soup 抓取网站的十大故事
- dll - 在 cygwin 中使用 gfortran 构建 Fortran dll 并将其链接到 fortran 代码
- jodatime - Joda-time:如何将本地时间转换为 UTC,然后仅使用毫秒转换为另一个本地时间?
- json - 将 cURL 转换为 Applescript
- android - 如何模拟 DataSource.Factory 进行单元测试
- html - 检查输入 html 中的属性以在块位置不同时使用 css 隐藏内容
- python - 创建一个新的 DataFrame 列并用 If 语句填充它 - Python
- javascript - Foreach 循环和 ajax 中的 Bootstrap Collapse