如何在Python中按字符切字符串?

时间:2019-03-16 08:38:54

标签: python

有一个包含一个或多个字符的字符串。我想对列表进行切片,以使相邻的相同字符位于同一元素中。例如:

'a' -> ['a']
'abbbcc' -> ['a', 'bbb', 'cc']
'abcabc' -> ['a', 'b', 'c', 'a', 'b', 'c']

如何在Python中做到这一点?

5 个答案:

答案 0 :(得分:18)

使用itertools.groupby

from itertools import groupby

s = 'abccbba'

print([''.join(v) for _, v in groupby(s)])
# ['a', 'b', 'cc', 'bb', 'a']

答案 1 :(得分:6)

可以通过re.finditer()

实现
import re
s='aabccdd'
print([m.group(0) for m in re.finditer(r"(\w)\1*", s)])
#['aa', 'b', 'cc', 'dd']

答案 2 :(得分:3)

无需任何模块,也可以使用for循环进行有趣的操作:

l=[]
str="aabccc"
s=str[0]
for c in str[1:]:

   if(c!=s[-1]):
        l.append(s)
        s=c
   else:
        s=s+c
l.append(s)
print(l)

答案 3 :(得分:3)

仅是另一种替代解决方案。您无需在python2中导入它。在python3中,您需要从functools导入。

from functools import reduce   # in python3
s='aaabccdddddaa'
reduce(lambda x,y:x[:-1]+[x[-1]+y] if len(x)>0 and x[-1][-1]==y else x+[y], s, [])

答案 4 :(得分:1)

import java.util.*;

public class BookStore
{
  public static void main(String[] args)
  {
   Author a1 = new Author("Malcom Gladwell");
   Author a2 = new Author("Steven Johnson");
   Author a3 = new Author("Mathias Johansson");
   Author a4 = new Author("Evan Ackerman");
   Author a5 = new Author("Erico Guizzo");
   Author a6 = new Author("Fan Shi");

   WrittenWork w1 = new Novel(a1, "What the Dog Saw and other adventures", 503);
   WrittenWork w2 = new Novel(a2, "How We Got to Now: Six Innovations That Made the Modern World", 320);
   WrittenWork w3 = new Novel(a2, "Everything Bad Is Good For you: How Today's Popular Culture is Actually Making us Smarter", 254);


   ArrayList<WrittenWork>products = new ArrayList<>();
   products.add(w1);
   products.add(w2);
   products.add(w3);

   for(WrittenWork w: products)
       System.out.println(w1.toString());
       System.out.println(w2.toString());
       System.out.println(w3.toString());

   }
 }