我必须拆分一个字符列表,以便在遇到元音时被切断。例如,像
这样的字符串toy = ['b', 'a', 'm', 'b', 'i', 'n', 'o']
输出应为
[('b', 'a'), ('m', 'b', 'i'), ('n', 'o')]
我试图运行2个循环,一个在另一个循环之后。
# usr/bin/env/python
apple = []
consonants = ('k', 'h', 'b', 'n')
vowels = ('i', 'a', 'u')
toy = ('k', 'h', 'u', 'b', 'a', 'n', 'i')
for i in range(len(toy)):
if i == 0:
pass
else:
if toy[i] in vowels:
for k in range(i - 1, len(toy)):
if toy[k - 1] in consonants:
n = toy[i - k:i - 1]
apple.append(n)
break
print apple
但是一旦元音到达,这不会让我走出循环。使用“bambino”示例,它给了我类似[('b', 'a'), ('b', 'a', 'm', 'b', 'i'), ('b', 'a', 'm', 'b', 'i', 'n', 'o')]
的东西。有人可以帮忙吗?
答案 0 :(得分:3)
你似乎过于复杂。一个简单的解决方案是 -
>>> toy = ['b', 'a', 'm', 'b', 'i', 'n', 'o']
>>> vowels = ['a','i','e','o','u']
>>> apples = []
>>> k = 0
>>> for i ,x in enumerate(toy):
... if x in vowels:
... apples.append(tuple(toy[k:i+1]))
... k = i+1
...
>>> apples
[('b', 'a'), ('m', 'b', 'i'), ('n', 'o')]
enumerate()
函数返回索引以及列表的当前元素。
答案 1 :(得分:2)
>>> result = []
>>> temp = []
>>> for char in toy:
... temp.append(char)
... if char.lower() in "aeiou":
... result.append(temp)
... temp = []
... if temp:
... result.append(temp)
...
>>> result
[['b', 'a'], ['m', 'b', 'i'], ['n', 'o']]
答案 2 :(得分:1)
你也可以使用它:
#usr/bin/env/python
apple = []
vowels = ('i', 'a', 'u')
toy = ('k', 'h', 'u', 'b', 'a', 'n', 'i')
collector = []
for i in toy:
collector.append(i)
if i in vowels:
apple.append(collector)
collector = []
print apple
结果:
[['k', 'h', 'u'], ['b', 'a'], ['n', 'i']]