如何在Python中拆分列表元素

如何在Python中拆分列表元素,python,function,Python,Function,我有下面的清单。我想像这样分开: [“动画”、“儿童”、“喜剧”、“冒险”、“儿童”、“幻想”、“喜剧”、“浪漫”、“喜剧”、“戏剧”] clist = ["Animation|Children's|Comedy", "Adventure|Children's|Fantasy", 'Comedy|Romance', 'Comedy|Drama'] for i,x in enumerate(clist): if '|' in x:

我有下面的清单。我想像这样分开:

[“动画”、“儿童”、“喜剧”、“冒险”、“儿童”、“幻想”、“喜剧”、“浪漫”、“喜剧”、“戏剧”]

clist = ["Animation|Children's|Comedy",

"Adventure|Children's|Fantasy",

'Comedy|Romance',

'Comedy|Drama']

 

for i,x in enumerate(clist):

    if '|' in x:

        clist[i] = x[:x.index('|')]
它返回以下内容:

[‘动画’、‘冒险’、‘喜剧’]

如果想要产生相同的结果,我建议在理解中使用拆分:

>>> [c.split("|")[0] for c in clist]
['Animation', 'Adventure', 'Comedy', 'Comedy']
如果要将所有单个列表元素而不是第一个元素展平为一个列表,则只需再进行一次嵌套理解:

>>> [g for c in clist for g in c.split("|")]
['Animation', "Children's", 'Comedy', 'Adventure', "Children's", 'Fantasy', 'Comedy', 'Romance', 'Comedy', 'Drama']

在Python中有很多方法可以做到这一点,但其中一种方法是使用列表理解,如下所示:

clist=[英语中的英语类型clist中的英语类型。拆分'|'] 这将把clist设置为[‘动画’、‘儿童’、‘喜剧’、‘冒险’、‘儿童’、‘幻想’、‘喜剧’、‘浪漫’、‘喜剧’、‘戏剧’]


为了解释这实际上是在做什么,它在clist中循环,将每个元素分配给glist变量,然后在每个|字符处拆分glist,然后在结果列表中为每个元素添加一个元素。

您可以利用嵌套的理解列表来实现以下目标:

clist=[动画|儿童|喜剧、冒险|儿童|幻想、'喜剧|浪漫'、'喜剧|戏剧'] l=[clist中用于子对象的管道元素用于子对象的管道元素。拆分'|'] 普林特 输出:[动画、儿童、喜剧、冒险、儿童、幻想、喜剧、浪漫、喜剧、戏剧]
是的,它可以工作,但它只返回唯一的值,我想查看所有元素。如果您只获得唯一的值,请确保您使用的是[],而不是{}……这是否回答了您的问题?