假设我有一个列表a = ["1a", "1b", "2b", "3c", "2d", "1g", "3d", "3g"]
,我想删除元素中具有相同coefficent / leading char的所有元素对,这样它就会给出["1g", "3g"]
之类的答案。
我将如何做这样的事情?
这是我到目前为止所达到的目标,但这是一团糟,并没有很好地运作
def pairs(l):
for x in range(len(l) -1,-1,-1):
counter=0
z=l[x][0]
for f in range(len(l)-1,-1,-1):
if z==(l[f][0]):
counter+=1
if counter%2==0:
for i in range(x,x-1,-1):
if z==(l[i][0]):
del (l[i])
elif counter%2==1 :
for i in range(x-1,x-2,-1):
if z==(l[i][0]):
del (l[i])
print(l)
答案 0 :(得分:0)
a = ["1a", "1b", "2b", "3c", "2d", "1g", "3d", "3g"]
coeffs = [a[0][0]] # collect coefficients
for i in a[1:]:
if i[0] not in coeffs: coeffs.append(i[0])
s = [[x for x in a if x[0] == i] for i in coeffs] # groups according to coefficients
# s = [["1a", "1b", "1g"], ["2b", "2d"], ["3c", "3d", "3g"]]
solution = [i[-1] for i in s if len(i)%2]
# ['1g', '3g']
答案 1 :(得分:0)
您可以根据第一个字符对列表元素进行分组,然后删除对。为此,itertools.groupby()
可以派上用场:
>>> a = ["1a", "1b", "2b", "3c", "2d", "1g", "3d", "3g"]
>>> a.sort()
>>> from itertools import groupby
>>> result = []
>>> for x, y in groupby(a, lambda x: x[0]):
... y = list(y)
... if len(y) % 2:
... result.append(y[-1])
...
>>> result
['1g', '3g']
答案 2 :(得分:0)
def deleter(char,seq):
if not seq or not isinstance(seq, list):
return []
else:
if char==seq[0][0]:
return function(char,seq[1:])
else:
return [seq[0]]+function(char,seq[1:])
我会使用recursive定义来解决它:
seq
为空则返回空列表else return the first element in the list seq in a form of list and add to it the call of function itself
修改强>: 我觉得你是一个新的程序员,如果是这样的话,我只想强调一下美丽和递归函数的优雅。这是一种解决问题的优雅数学方法。如果他们对离散数学中的 proof by indcution 有任何熟悉,那么新程序员,前程序员和数学家都可以轻松阅读您的代码。在大多数情况下,您基本上遵循以下伪代码:
答案 3 :(得分:0)
这不必过于复杂。按字母的前导字符映射单词,但如果字典已有该键,则删除现有的项目。
def pairs(a):
result = {}
for word in a:
leading_char = word[0]
if result.has_key(leading_char):
del result[leading_char]
else:
result[leading_char] = word
return result.values()
a = ["1a", "1b", "2b", "3c", "2d", "1g", "3d", "3g"]
print pairs(a)