在列表中,如何将每个字符串(使用混合特殊字符)分隔为单个字符?

2024-06-16 10:45:56 发布

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

假设,我想将下面的列表拆分为单个字符。你知道吗

mylist = [('dog', 'camel'), ('horse'), ('List_of_people_saved_by_Oskar'), 'mouse_bear', 'lion tiger rabbit', 'ant']

这就是我迄今为止所尝试的:

L1 = [animal for word in mylist for animal in word.split('_')]
print(L1)

输出应如下所示:

`['dog', 'camel', 'horse', 'List', 'of', 'people', 'saved', 'by', 'Oskar', 'mouse', 'bear', 'lion', 'tiger' 'rabbit', 'ant']`

但我得到一个错误:

AttributeError: 'tuple' object has no attribute 'split'

Tags: ofbypeoplelistbearrabbittigerdog
3条回答

您可以使用re.findall(r'[^_ ]+', word)来拆分下划线或空格分隔的单词。还可以添加另一个理解层来展平可能的字符串元组:

import re
L1 = [animal for item in mylist for word in (item if isinstance(item, (tuple, list)) else (item,)) for animal in re.findall(r'[^_ ]+', word)]

L1将变成:

['dog', 'camel', 'horse', 'List', 'of', 'people', 'saved', 'by', 'Oskar', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']

你搞混了要去哪里。你知道吗

[animal.split('_') for word in mylist for animal in word]

另外一个问题是("horse")不是元组;("horse",)是元组。因此,("horse")仅仅是括号中的"horse",并且for animal in word将枚举"horse"中的单个字母,而不是返回一个"horse"动物。你知道吗

如果要按_以外的字符拆分,可以使用re.split和字符类:

import re
[re.split(r'[_ ]', animal) for word in mylist for animal in word]

如果您真的打算让非配对动物而不是成为元组,那么您必须特别处理这些情况:

[re.split(r'[_ ]', animal)
    for word in mylist
    for animal in (word if isinstance(word, tuple) else (word,))]

好吧,这里有一个更可读的代码,因为我真的不喜欢有一个内联代码的想法,不管它有多高效或更快。另外,您可能更容易理解,而且不需要库导入。你知道吗

代码:

mylist = [('dog', 'camel'), ('horse'), ('List_of_people_saved_by_Oskar'), 'mouse_bear', 'lion tiger rabbit', 'ant']
new_list = []

for items in mylist:
    if type(items) == tuple:
        for animals in items:
            new_list.append(animals)
    elif '_' in items:
        new_animal = items.split('_')
        for animals in new_animal:
            new_list.append(animals)

    elif ',' in items:
        new_animal = items.split(',')
        for animals in new_animal:
            new_list.append(animals)

    elif ' ' in items:
        new_animal = items.split(' ')
        for animals in new_animal:
            new_list.append(animals)
    else:
        new_list.append(items)
print(new_list)

输出:

['dog', 'camel', 'horse', 'List', 'of', 'people', 'saved', 'by', 'Oskar', 'mouse', 'bear', 'lion', 'tiger', 'rabbit', 'ant']

相关问题 更多 >