将字符串映射到对列表中

时间:2017-01-29 17:31:58

标签: python python-3.x map-function

我有一个for循环遍历字符串并返回每个字符对和下一个字符对:

>>> word = 'abcdef'
>>> for i in range(len(word)-1):
...     print word[i:i+2]
...
ab
bc
cd
de
ef

是否可以使用地图/滤镜组合来编写?我在弄清楚如何获得下一个角色而不是使用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

3 个答案:

答案 0 :(得分:5)

这解决了您的问题:

list(map(lambda x, y: x+y, word[:-1], word[1:]))

忽略第一个可迭代的单词的最后一个元素(单词[: - 1])

答案 1 :(得分:3)

您可以zip 字[1:] ,然后使用地图加入相邻的字母:

>>> 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']

可以使用@Chepner评论的连接函数删除额外的lambda

>>> 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']

答案 2 :(得分:0)

这是一个很好的解决方案,因为它具有内存效率,并且不必重复列表来组合它们。

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')]