【发布时间】:2016-02-21 07:11:27
【问题描述】:
编写一个接受输入列表并返回新列表的函数 仅包含唯一元素(元素应该只出现 列表中的一次,并且必须保留元素的顺序 作为原始列表。 )。
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: 列表索引超出范围
【问题讨论】:
-
请注意,
list是关键字 -
@Obsidian no
list不是关键字 -
List 是内置函数的名称。可以重新定义,但不推荐。
-
@helloV 对不起。意味着一个内置函数
-
您的列表索引范围错误是由于
i正在遍历所有元素索引,因此当它位于最后一个元素上时,i+1将超出范围。但更大的问题是您只检查相邻元素的重复项。如果您的列表是[1, 2, 1]怎么办?你的算法将返回所有三个元素,我不相信你想要。
标签: python python-2.7 python-3.x