【问题标题】:How do I split an element of a list into multiple elements in python 3?如何在 python 3 中将列表的元素拆分为多个元素?
【发布时间】:2016-03-23 08:41:18
【问题描述】:

我想知道如何将列表中的单个元素拆分为多个不同的元素。例如:

list=['My phone is cracked']  

我想变成这样:

list=['My','phone','is','cracked']

【问题讨论】:

标签: arrays python-3.x arraylist elements


【解决方案1】:
list=['My phone is cracked']
list = list[0].split(" ")
print(list)

这将打印您想要的输出。 在list 之后有[0] 的原因是因为split 仅适用于字符串,因此您必须取出数组中的第一个值,并将其视为数组。 希望这会有所帮助!:)

【讨论】:

    【解决方案2】:

    您可以使用 split() 方法 (https://docs.python.org/3.5/library/stdtypes.html#str.split)。

    list[0].split()

    【讨论】:

      【解决方案3】:

      我假设请求是遍历列表并将元素拆分为多个元素,如果存在,则使用“”,否则元素原样。

      所以

      ['我的手机被破解', '新手机', '收藏']

      变成

      ['My', 'phone', 'is', 'cracked', 'new', 'phone', 'collection']

      你可以这样做:

      list1 = ['My phone is cracked', 'new phone', 'collection']
      new_list1 = [y for x in list1 for y in x.split(' ')]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-25
        • 1970-01-01
        • 2017-03-14
        • 2021-08-10
        • 2020-06-08
        • 1970-01-01
        相关资源
        最近更新 更多