简体   繁体   English

Pandas 添加以列出列表中相邻元素的组合

[英]Pandas add to list the combination of adjacent elements in a list

What I want to do seems simple, say I have an existing list of words:我想做的事情似乎很简单,假设我有一个现有的单词列表:

original_List = ['a', 'b', 'c', 'd'] original_List = ['a', 'b', 'c', 'd']

I want to transform that list into:我想将该列表转换为:

new_List = ['a', 'b', 'c', 'd', 'a b', 'b c', 'c d'] new_List = ['a', 'b', 'c', 'd', 'a b', 'b c', 'c d']

So in te new list we took the original list and then appended to it 2 elements at a time.因此,在新列表中,我们获取了原始列表,然后一次向其附加 2 个元素。

Is there a simple way to do this?有没有一种简单的方法可以做到这一点?

One approach:一种方法:

original_list = ['a', 'b', 'c', 'd']

new_list = original_list + [f"{a} {b}" for a, b in zip(original_list, original_list[1:])]
print(new_list)

Output输出

['a', 'b', 'c', 'd', 'a b', 'b c', 'c d']

Or, as an alternative, use itertools.pairwise :或者,作为替代方案,使用itertools.pairwise

from itertools import pairwise
new_list = original_list + [f"{a} {b}" for a, b in pairwise(original_list)]
print(new_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM