我需要创建一个包含来自另一个列表的唯一值的新列表,还必须维护订单。我的代码: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。那么有人可以让我知道我的原始代码是否可以工作吗?
1 回答

慕尼黑5688855
TA贡献1848条经验 获得超2个赞
尝试这个
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]
添加回答
举报
0/150
提交
取消