如何在Python中连接元素级列表?
我有一个字符串列表,我想通过以下方式连接列表中的元素:如何在Python中连接元素级列表?,python,list,Python,List,我有一个字符串列表,我想通过以下方式连接列表中的元素: before=['a','b','c','d'] after=['ab','bc','cd'] 我不知道如何调用上述操作 但是,我尝试使用范围方法: after=[before[i]+before[i+1]表示范围内的i(0,len(before),2)] 但是它的结果是:after=['ab','cd']您的方法不允许重叠,因为您的索引增加了2 一个快速解决方案是 after = [before[i]+before[i+1] for
before=['a','b','c','d']
after=['ab','bc','cd']
我不知道如何调用上述操作
但是,我尝试使用范围方法:
after=[before[i]+before[i+1]表示范围内的i(0,len(before),2)]
但是它的结果是:
after=['ab','cd']
您的方法不允许重叠,因为您的索引增加了2
一个快速解决方案是
after = [before[i]+before[i+1] for i in range(len(before)-1)]
但我更喜欢zip
列表本身的切片版本:
before = ['a', 'b', 'c', 'd']
after = [a+b for a,b in zip(before,before[1:])]
>>> after
['ab', 'bc', 'cd']
你的方法不允许重叠,因为你的索引增加了2 一个快速解决方案是
after = [before[i]+before[i+1] for i in range(len(before)-1)]
但我更喜欢zip
列表本身的切片版本:
before = ['a', 'b', 'c', 'd']
after = [a+b for a,b in zip(before,before[1:])]
>>> after
['ab', 'bc', 'cd']
您还可以使用:
输出
['ab', 'bc', 'cd']
进一步
您还可以使用:
输出
['ab', 'bc', 'cd']
进一步
在中,您可以使用一个有用的配方:
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
>>> map(lambda x: ''.join(x), pairwise(before))
['ab', 'bc', 'cd']
在中,您可以使用一个有用的配方:
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
>>> map(lambda x: ''.join(x), pairwise(before))
['ab', 'bc', 'cd']