我有两个列表,我使用listA.extend(listB)连接。
扩展listA时我需要实现的是将listA的最后一个元素与listB的第一个元素连接起来
我的列表示例如下
listA = ... '1633437.0413', '5417978.6108', '1633433.2865', '54']
listB = ['79770.3904', '1633434.364', '5417983.127', '1633435.2672', ...
显然,当我延伸时,我得到以下(注意54)
'5417978.6108', '1633433.2865', '54', '79770.3904', '1633434.364', '5417983.127
以下是我想要实现的最后和第一个元素连接的内容
[...5417978.6108', '1633433.2865', '*5479770.3904*', '1633434.364', '5417983.127...]
任何想法?
答案 0 :(得分:4)
您可以分两步完成:
A[-1] += B[0] # update the last element of A to tag on contents of B[0]
A.extend(B[1:]) # extend A with B but exclude the first element
示例:
>>> A = ['1633437.0413', '5417978.6108', '1633433.2865', '54']
>>> B = ['79770.3904', '1633434.364', '5417983.127', '1633435.2672']
>>> A[-1] += B[0]
>>> A.extend(B[1:])
>>> A
['1633437.0413', '5417978.6108', '1633433.2865', '5479770.3904', '1633434.364', '5417983.127', '1633435.2672']
答案 1 :(得分:2)
newlist = listA[:-1] + [listA[-1] + listB[0]] + listB[1:]
或者如果你想扩展listA“inplace”
listA[-1:] = [listA[-1] + listB[0]] + listB[1:]
答案 2 :(得分:0)
带有列表理解的单行(实际上只是为了列表理解:):)
[(x + listB[0]) if i == len(listA) - 1 else x for i, x in enumerate(listA)] + listB[1:]