如何提取由散列符号包围的列表中的对列表?

2024-10-03 19:23:26 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我想从下面的“令牌”列表中提取配对列表:

tokens = ['0', '#', 'a', 'b', '#', '#', 'c', '#',  '#', 'g', 'h', 'g', '#']

pair_list = [['a', 'b'], ['c'],  ['g', 'h', 'g']]

我试图做下面的事情,但没有成功:

hashToken_begin_found = True
hashToken_end_found = False

previous_token = None

pair_list = []

for token in tokens:

    if hashToken_begin_found and not hashToken_end_found and previous_token and previous_token == '#':
        hashToken_begin_found = False
    elif not hashToken_begin_found:
        if token == '#':
            hashToken_begin_found = True
            hashToken_end_found = True
        else:
            ...

补充:

我的实际问题更复杂。这对符号中包含的是社交媒体中的单词,比如推特上的散列短语,但它们不是英语。为了说明问题,我把问题简化了。逻辑就像我写的那样:找到每一对的“开始”和“结束”,并将其提取出来。在我的数据中,一对散列标签中的任何内容都是一个短语,即我住在美国和纽约!。我要去美国和纽约。没有正则表达式。这些单词已经在列表中


Tags: andtokenfalsetrue列表ifnotlist
3条回答

我认为你把问题复杂化了。将解析器视为一个非常简单的状态机。你要么在子列表中,要么不在子列表中。每次你点击一个散列,你就会切换状态

输入子列表时,创建一个新列表。在子列表中时,附加到当前列表。就这样。以下是一个示例:

pair_list = []
in_pair = False
for token in tokens:
    if in_pair:
        if token == '#':
            in_pair = False
        else:
            pair_list[-1].append(token)
    elif token == '#':
        pair_list.append([])
        in_pair = True

您可以在一行中尝试itertools.groupby

from itertools import groupby
tokens = ['0', '#', 'a', 'b', '#', '#', 'c', '#',  '#', 'g', 'h', 'g', '#']
print([list(y) for x, y in itertools.groupby(tokens, key=lambda x: x.isalpha()) if x])

输出:

[['a', 'b'], ['c'], ['g', 'h', 'g']]

I按值为字母的连续组分组

如果要使用for循环,可以尝试:

l = [[]]
for i in tokens:
    if i.isalpha():
        l[-1].append(i)        
    else:
        if l[-1]:
            l.append([])
print(l[:-1])

输出:

[['a', 'b'], ['c'], ['g', 'h', 'g']]

另一种方式(Try it online!):

it = iter(tokens)
pair_list = []
while '#' in it:
    pair_list.append(list(iter(it.__next__, '#')))

还有一个(Try it online!):

pair_list = []
try:
    i = 0
    while True:
        i = tokens.index('#', i)
        j = tokens.index('#', i + 1)
        pair_list.append(tokens[i+1 : j])
        i = j + 1
except ValueError:
    pass

相关问题 更多 >