算是做的第一个Python练习了,对我这个菜鸟来说还是学到不少东西的。
题目:
You are given a list of integers. For this task, you should return a list consisting of only the non-unique elements in this list. To do so you will need to remove all unique elements (elements which are contained in a given list only once). When solving this task, do not change the order of the list. Example: [1, 2, 3, 1, 3] 1 and 3 non-unique elements and result will be [1, 3, 1, 3].
Input: A list of integers.
Output: A list of integers.
我的解答:
def checkio(data):
#Your code here
#It's main function. Don't remove this function
#It's using for auto-testing and must return a result for check.
n=0
data1=list()
while n<len(data):
if(data.count(data[n])>1):
data1.append(data[n])
n=n+1
return data1
改进:
基于对语言的不熟悉,比较好的做法应该是把while语句改成for语句。
另有高人解法:
checkio=lambda d:[x for x in d if d.count(x)>1]
学习到的相关内容:list,lamda,链表推导式