你可以认为这个问题是以前的。回答了,但是最后一个版本不能用2位数给定一个数字列表,查找并打印其中只出现一次的元素。这些元素应该按照它们在原始列表中出现的顺序打印。
所以这是我的代码(被其他pythoneers修复)
a = [int(s) for s in input().split()]
sortedLst = sorted(a)
unique = []
uniqueOrd = []
for i in range(len(a) - 2):
if sortedLst[i + 1] != sortedLst[i] and sortedLst[i + 1] != sortedLst[i + 2]:
unique.append(sortedLst[i + 1])
for num in a:
if num in unique:
uniqueOrd.append(num)
print(*uniqueOrd)
但是输出不工作与2位数的数字,我怎么能修复这个错误?
您不必费力从长列表中找到uniques
,只需考虑collections
- Counter中的漂亮库即可。它更快,更python化。
A = [int(s) for s in input().split()]
sortedLst = sorted(A) # this is just to confirm your inputs..
from collections import Counter
counts = Counter(A)
print(counts)
uniques = [k for k, v in counts.items() if v == 1] # just check the frequency (v)
print(uniques)
尝试如下输入:2 3 1 4 22 33 44 55 33 22
[2, 3, 1, 4, 44, 55]