将字符串映射到对列表
Mapping a string into a list of pairs
我有一个 for 循环遍历一个字符串和每个字符的 returns 对以及下一个字符:
>>> word = 'abcdef'
>>> for i in range(len(word)-1):
... print word[i:i+2]
...
ab
bc
cd
de
ef
是否可以使用 map/filter 组合来写这个?我在弄清楚如何获取下一个字符而不是使用 i+2
.
时遇到问题
我试过两次传递这个词来将它们映射到一起:
>>> word = 'abcdef'
>>> map(lambda x, y: x+y, word, word[1:])
但我不确定如何避免 str 和 None:
的连接错误
>>> map(lambda x, y: x+y, word, word[1:])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: cannot concatenate 'str' and 'NoneType' objects
可以zip
word和word[1:]然后用map连接相邻的字母:
>>> word = 'abcdef'
>>> map(lambda x: ''.join(x), zip(word, word[1:]))
# zip function goes as far as the shortest argument, so there is no need to remove the last
# element from word here
# ['ab', 'bc', 'cd', 'de', 'ef']
额外的 lambda
可以只用 @Chepner 评论的 join 函数删除:
>>> map(''.join, zip(word, word[1:]))
# ['ab', 'bc', 'cd', 'de', 'ef']
您还可以将 list-comprehension 与 zip
函数一起使用:
[x + y for x, y in zip(word, word[1:])]
# ['ab', 'bc', 'cd', 'de', 'ef']
这解决了您的问题:
list(map(lambda x, y: x+y, word[:-1], word[1:]))
只是忽略第一个可迭代的 word 的最后一个元素 (word[:-1])
这是一个很好的解决方案,因为它节省了内存,而且不必复制列表来组合它们。
def last_and_current(iterator):
iterator = iter(iterator)
last = next(iterator)
for current in iterator:
yield last, current
last = current
print [l + c for l, c in last_and_current('abcdef')]
我有一个 for 循环遍历一个字符串和每个字符的 returns 对以及下一个字符:
>>> word = 'abcdef'
>>> for i in range(len(word)-1):
... print word[i:i+2]
...
ab
bc
cd
de
ef
是否可以使用 map/filter 组合来写这个?我在弄清楚如何获取下一个字符而不是使用 i+2
.
我试过两次传递这个词来将它们映射到一起:
>>> word = 'abcdef'
>>> map(lambda x, y: x+y, word, word[1:])
但我不确定如何避免 str 和 None:
的连接错误>>> map(lambda x, y: x+y, word, word[1:])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: cannot concatenate 'str' and 'NoneType' objects
可以zip
word和word[1:]然后用map连接相邻的字母:
>>> word = 'abcdef'
>>> map(lambda x: ''.join(x), zip(word, word[1:]))
# zip function goes as far as the shortest argument, so there is no need to remove the last
# element from word here
# ['ab', 'bc', 'cd', 'de', 'ef']
额外的 lambda
可以只用 @Chepner 评论的 join 函数删除:
>>> map(''.join, zip(word, word[1:]))
# ['ab', 'bc', 'cd', 'de', 'ef']
您还可以将 list-comprehension 与 zip
函数一起使用:
[x + y for x, y in zip(word, word[1:])]
# ['ab', 'bc', 'cd', 'de', 'ef']
这解决了您的问题:
list(map(lambda x, y: x+y, word[:-1], word[1:]))
只是忽略第一个可迭代的 word 的最后一个元素 (word[:-1])
这是一个很好的解决方案,因为它节省了内存,而且不必复制列表来组合它们。
def last_and_current(iterator):
iterator = iter(iterator)
last = next(iterator)
for current in iterator:
yield last, current
last = current
print [l + c for l, c in last_and_current('abcdef')]