CheckiO 是面向初学者和高级程序员的编码游戏,使用 Python 和 JavaScript 解决棘手的挑战和有趣的任务,从而提高你的编码技能,传送门:https://checkio.org/,本博客主要记录自己在闯关时的做题思路和实现代码,同时也学习学习其他大神写的代码。
题目描述
【Non-unique Elements】:你将得到一个含有整数(X)的非空列表。在这个任务里,你应该返回在此列表中的非唯一元素的列表。要做到这一点,你需要删除所有独特的元素(这是包含在一个给定的列表只有一次的元素)。解决这个任务时,不能改变列表的顺序。例如:[1,2,3,1,3] 1和3是非唯一元素,结果将是 [1, 3, 1, 3]。
【输入】:一个含有整数的列表
【输出】:去除只出现过一次的元素后的列表
【前提】:0 < |X| < 1000
【范例】:
checkio([1, 2, 3, 1, 3]) == [1, 3, 1, 3]
checkio([1, 2, 3, 4, 5]) == []
checkio([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5]
checkio([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9]
解题思路
循环访问列表的每一个元素,利用 count()
方法统计元素出现的次数,若出现次数大于1,就将这些元素添加到一个新列表,最后返回该列表即可
代码实现
#Your optional code here
#You can import some modules or create additional functions
def checkio(data: list) -> list:
data2 = []
for i in data:
if data.count(i) > 1:
data2.append(i)
return data2
#Some hints
#You can use list.count(element) method for counting.
#Create new list with non-unique elements
#Loop over original list
if __name__ == "__main__":
#These "asserts" using only for self-checking and not necessary for auto-testing
assert list(checkio([1, 2, 3, 1, 3])) == [1, 3, 1, 3], "1st example"
assert list(checkio([1, 2, 3, 4, 5])) == [], "2nd example"
assert list(checkio([5, 5, 5, 5, 5])) == [5, 5, 5, 5, 5], "3rd example"
assert list(checkio([10, 9, 10, 10, 9, 8])) == [10, 9, 10, 10, 9], "4th example"
print("It is all good. Let's check it now")
大神解答
大神解答 NO.1
def checkio(data):
return [i for i in data if data.count(i) > 1]
大神解答 NO.2
from collections import Counter
def checkio(data):
counter = Counter(data)
return [item for item in data if counter[item] > 1]