python - 列表从 Python 中的另一个列表返回唯一值
问题描述
我需要创建一个新列表,其中包含另一个列表中的唯一值,还必须保持顺序。我的代码:
def unique_elements(a):
newlist = []
for i in range(len(a)):
if a[i] not in a[i+1:] and a[i-1::-1] :
newlist.append(a[i])
return newlist
输出是:
unique_elements([1,2,2,3,4,3])
[1, 2, 4, 3]
我得到了半正确的结果,因为这个顺序没有得到维护。正确的输出应该是:
[1,2,3,4]
有人可以让我知道我哪里出错了。
我从其他帖子中得到了这个解决方案:
def unique_elements(a):
newlist = []
for i in a:
if i not in newlist:
newlist.append(i)
return newlist
另外,我还没有接触过 Python 中的 SET。那么有人可以让我知道我的原始代码是否可以工作吗?
解决方案
尝试这个
def unique_elements(a):
newlist = []
for i in a:
if i not in newlist:
newlist.append(i)
return newlist
xyz = [1,1,2,4,6,2,2,4,5]
print(unique_elements(xyz))
输出:
[1, 2, 4, 6, 5]
推荐阅读
- laravel - 在新的 laravel 文件中执行“npm run”时出错 - 找不到模块 npm-cli.js
- html - 使用 %userprofile% 的数据源 iMacro
- javascript - 使用 javascript SDK 从 facebook graph api 获取个人资料图片
- kubernetes - Kubernetes 仪表板(Web UI)不工作
- python - 用于迁移学习的 Keras input_tensor 形状
- java - Jsoup getElementsByAttributeValueMatching 不起作用
- c++ - 以两个 std::vector 和一个常量作为参数的 std::transform
- jquery - 如何使用 jquery 将 sidemenuTab 显示到当前选项卡中?
- angular - 产品的角度复选框过滤器
- android - 过滤正在上传的图像