在 C# 中,如何获取通过落在某个元素之间分组的新元素列表。例如,如果我的列表是 ['visit', 'houston', 'and', 'san', 'antonio', 'and', 'austin', 'and', 'corpus', 'christi']
我想将“and”之间的城市提取到一个在“and”之间分组的新列表中,这样两个单词名称城市就在一个组中
在 python 中,您可以使用 itertools,但如何在 c# 中实现此目的?
import itertools as itt
List =['visit', 'houston', 'and', 'san', 'antonio', 'and', 'austin', 'and', 'corpus', 'christi']
>>> [list(g) for k, g in itt.groupby(L, key=lambda word: word=='and') if not k]
结果-
[['visit', 'houston'], ['san', 'antonio'], ['austin'], ['corpus', 'christi']]
最佳答案
将它们组合成一个字符串(或者如果它们是这样开始的,则保持原样),然后用 and
分割它,并再次分割每个子字符串:
var words = new[] { "visit", "houston", "and", "san", "antonio", "and", "austin", "and", "corpus", "christi" };
var sentence = string.Join(' ', words); // "visit houston and san .... christi"
var cities = sentence.Split("and", StringSplitOptions.None)
.Select(x => x.Split(' ', StringSplitOptions.RemoveEmptyEntries))
.ToArray();
请注意,如果您的输入中包含空格(例如 ...、“and”、“san antonio”、...
),则可能需要进行一些调整。
关于c# 获取在列表中的某个元素之间分组的新元素列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54260298/