0

我必须使用字典编写一个方法,该方法接受一个列表a并返回一个列表,其中包含a出现一次的元素,并且元素的出现顺序应与它们在a. 我认为方向正确吗?这是我的代码:

def only_once(a):
    d = {}
    for i in a:
        d['value'] = i
    m = range(len(a))
    for num in m:
        d['key'] = num
    return d.value  

如何从列表中获取元素a并生成值?

4

3 回答 3

2

itertools有这个任务的秘诀

def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in ifilterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

顺便说一句,由于您希望顺序相同,因此字典在这里无济于事。Adict不维护任何秩序。

于 2013-10-13T21:45:49.500 回答
0

这是一个幼稚的解决方案。它几乎使用 dict 作为 a set,这很愚蠢,因为 python 有集合。但是,嘿。

def only_once(a):
  d = {}
  for i in a:
    d.setdefault(i,0)
    d[i] += 1
  return [i for i in a if d[i] == 1]
于 2013-10-13T21:54:05.650 回答
0

这是我使用 dict 理解并按相应值对 dict 键进行排序的解决方案:

def only_once(a):
   # create the dictionary using dict comprehension;
   # add to the dictionary only if the number of occurences
   # equals one
   d = {x:a.index(x) for x in a if a.count(x) == 1}

   # retrieve the dictionary keys as list and sort them by the value
   # of their assigned dictionary values
   return sorted(d.keys(), key = d.get)

but I agree that dict is not the most fortunate choice of datastructure for solving this problem.

于 2013-10-14T11:16:14.730 回答