[英]Python, How to concatenate successive and similar elements of a list?
例如:输入是:
['1','2','3','3','7','7','4']
我想要这个 output:
['1','2','33','77','4']
我做了这个 function 但它只有在列表的 len 是 2 的幂时才有效
def function(L):
M=[]
for i in range(0,len(L),2):
if L[i]==L[i+1]:
M.append(L[i]+L[i+1])
else:
M.append(L[i])
M.append(L[i+1])
return M
import itertools
def function(L):
return [ ''.join(g) for k, g in itertools.groupby(L) ]
print(function(['1','2','3','3','7','7','4']))
计数器可能会很好地为您服务,但是如果您想要一个类似于您的解决方案并且无需导入,请知道 while 循环更适合您的代码:
def function(L):
M = []
i = 0
while i < len(L):
if i+1 < len(L):
if L[i]==L[i+1]:
M.append(L[i]+L[i+1])
i += 1
else:
M.append(L[i])
i += 1
else:
M.append(L[i])
break
return M
这不是解决问题的最有效方法,而是直接来自您编写的代码,只是为了说明在这种情况下您可以如何使用 while 循环而不是找到解决方案(同样,可能不是最好的解决方案) for 循环,因为它允许您在循环内修改 i 的值。
此解决方案连接列表中的所有相似元素。 我使用 Collections 模块来识别相似的元素并根据您的需要连接
>>> from collections import Counter
>>>
>>> a = ['1','2','3','3','7','7','4']
>>> Counter(a)
Counter({'3': 2, '7': 2, '1': 1, '2': 1, '4': 1})
>>> b = Counter(a)
>>> for ele in Counter(a):
... print (ele, b[ele])
...
1 1
2 1
3 2
7 2
4 1
>>>
>>> c = [str(ele)*int(b[ele]) for ele in b]
>>> c
['1', '2', '33', '77', '4']
>>>
我建议将问题分成两个子问题。 一种是连接一系列相似的元素(辅助功能),另一种是通过列表前进到下一个不相似的元素并创建结果列表:
def function(L) :
if L == [] :
return []
else :
(j,val) = concatvalues(L)
M = [val]
M.extend(function(L[j:]))
return M
def concatvalues(L) :
j = 1
s = L[0]
while j < len(L) and L[j] == L[0] :
s += L[j]
j += 1
return (j,s)
print(function(['1','2','3','3','7','7','4']))
这 function 作品
def function(L):
M = []
K = L
for el in K:
repet = K.count(el)
K.remove(el)
M.append(el*repet)
return M
*更新
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.