[英]Python - Seperate letters in a list
代码:
a = ['a', 'b', 'c', '\n', 'd', 'e', 'f', '\n', 'g', 'h', 'i', '\n']
words = []
for letter in a:
if letter == "\n":
word.append(a[0:a.index(letter)])
del a[0:a.index(letter)+1]
print(a)
print(words)
Output:
['a', 'b', 'c', '\n', 'd', 'e', 'f', '\n', 'g', 'h', 'i', '\n']
['d', 'e', 'f', '\n', 'g', 'h', 'i', '\n']
['g', 'h', 'i', '\n']
[['a', 'b', 'c'], ['d', 'e', 'f']]
我希望最终的单词列表是[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
. append 为什么没有最后一项?
有 8 次迭代而不是 12 次,因为您在循环期间更改了列表。
words = []
a = [
'a', 'b', 'c', '\n',
'd', 'e', 'f', '\n',
'g', 'h', 'i', '\n'
]
for i, letter in enumerate(a) :
print(a, "\n", (
# padding to shift i to the right
' ' * (len(str(a[0:i])) + (i and 2))
), i, sep = "")
if letter == "\n" :
words.append(a[0:a.index(letter)])
del a[0:a.index(letter)+1]
print(
"# '\\n' found at", i,
"=> words +=", words[-1],
'\n'
)
print(words)
正如您在下面看到的,在i = 7
之后没有任何内容可以循环,因为len(a) = 8
。
['a', 'b', 'c', '\n', 'd', 'e', 'f', '\n', 'g', 'h', 'i', '\n']
0
['a', 'b', 'c', '\n', 'd', 'e', 'f', '\n', 'g', 'h', 'i', '\n']
1
['a', 'b', 'c', '\n', 'd', 'e', 'f', '\n', 'g', 'h', 'i', '\n']
2
['a', 'b', 'c', '\n', 'd', 'e', 'f', '\n', 'g', 'h', 'i', '\n']
3
# '\n' found at 3 => words += ['a', 'b', 'c']
['d', 'e', 'f', '\n', 'g', 'h', 'i', '\n']
4
['d', 'e', 'f', '\n', 'g', 'h', 'i', '\n']
5
['d', 'e', 'f', '\n', 'g', 'h', 'i', '\n']
6
['d', 'e', 'f', '\n', 'g', 'h', 'i', '\n']
7
# '\n' found at 7 => words += ['d', 'e', 'f']
[['a', 'b', 'c'], ['d', 'e', 'f']]
一种可能的解决方法是停止改变列表(这是大多数人所做的)。
words = []
a = [
'a', 'b', 'c', '\n',
'd', 'e', 'f', '\n',
'g', 'h', 'i', '\n'
]
for i, letter in enumerate(a) :
if letter == "\n" :
words.append(a[i-3:i])
print(words)
或者您可以将 for 替换for
while
。
words = []
a = [
'a', 'b', 'c', '\n',
'd', 'e', 'f', '\n',
'g', 'h', 'i', '\n'
]
while a != [] :
words.append(a[0:a.index('\n')])
del a[0:a.index('\n')+1]
print(words)
如果您不明白,请发表评论:-)
拥有您想要的最终列表的解决方案:
a = ['a', 'b', 'c', '\n', 'd', 'e', 'f', '\n', 'g', 'h', 'i', '\n']
words = []
group = []
for letter in a:
if letter == "\n":
words.append(group)
group = []
else:
group.append(letter)
print(words)
output 是:
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
列表中的每个元素都是字母,那么
>>> a = ['a', 'b', 'c', '\n', 'd', 'e', 'f', '\n', 'g', 'h', 'i', '\n']
>>> list(map(list, ''.join(a).split()))
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.