编写一个函数,它接受一个输入列表并返回一个仅包含唯一元素的新列表(元素应该只在列表中出现一次,并且元素的顺序必须保留为原始列表。)。
def unique_elements (list):
new_list = []
length = len(list)
i = 0
while (length != 0):
if (list[i] != list [i + 1]):
new_list.append(list[i])
i = i + 1
length = length - 1
'''new_list = set(list)'''
return (new_list)
#Main program
n = int(input("Enter length of the list: "))
list = []
for i in range (0, n):
item = int(input("Enter only integer values: "))
list.append(item)
print ("This is your list: ", list)
result = unique_elements (list)
print (result)
我被这个错误困住了:
IndexError:列表索引超出范围
原文由 Karan Thakkar 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是最简单的方法: