如何使用python将数组中的字符串切分为另一个数组

2024-05-18 16:16:31 发布

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

我想把一个列表中字符串的某些部分切成另一个列表, 例如,考虑其是列表数据:

data = ["xbox 360 | 13000 | new","playstation 4 | 30000 | new","playstation 3 | 30000 | old","playstation 2 | 30000 | old"]

我想把每个组件分成三部分

product = ["xbox 360","playstation 4","playstation 3","playstation 2"]
cost = ["13000","30000","30000","30000"]
condition = ["new","new","old","old"]

请帮帮我


Tags: 数据字符串列表newdata组件productcondition
3条回答

@surya,您可以尝试以下两种方法中的任何一种。第一个很短,只需执行一行语句就可以给出所有3个列表。我使用了列表理解reduce()函数的概念。你知道吗

Use split() to get the words separated with | for each of the list items.

Use strip() to remove leading/trailing whitespaces.

第一路(单行语句)

Just use product, cost, condition = reduce(lambda s1, s2: [s1[index] + [item.strip()] for index, item in enumerate(s2.split('|'))], data,[[], [], []]); and it will give your lists.

>>> data = ["xbox 360 | 13000 | new","playstation 4 | 30000 | new","playstation 3 | 30000 | old","playstation 2 | 30000 | old"]
>>>
>>> product, cost, condition = reduce(lambda s1, s2: [s1[index] + [item.strip()] for index, item in enumerate(s2.split('|'))], data,[[], [], []]);
>>>
>>> product
['xbox 360', 'playstation 4', 'playstation 3', 'playstation 2']
>>>
>>> cost
['13000', '30000', '30000', '30000']
>>>
>>> condition
['new', 'new', 'old', 'old']
>>>

第二条路

>>> data = ["xbox 360 | 13000 | new","playstation 4 | 30000 | new","playstation 3 | 30000 | old","playstation 2 | 30000 | old"]
>>>
>>> product = []
>>> cost = []
>>> condition = []
>>>
>>> for s in data:
...     l = [item.strip() for item in s.split("|")]
...     product.append(l[0])
...     cost.append(l[1])
...     condition.append(l[2])
...
>>> product
['xbox 360', 'playstation 4', 'playstation 3', 'playstation 2']
>>>
>>> cost
['13000', '30000', '30000', '30000']
>>>
>>> condition
['new', 'new', 'old', 'old']
>>>
>>>

您可以循环浏览数据列表,然后拆分每个元素。然后可以使用.append()将数据添加到productcostcondition列表中:

data = ["xbox 360 | 13000 | new","playstation 4 | 30000 | new","playstation 3 | 30000 | old","playstation 2 | 30000 | old"]
product = []
cost = []
condition = []
for string in data:
    strSplit = string.split(" | ")
    product.append(strSplit[0])
    cost.append(strSplit[1])
    condition.append(strSplit[2])

print(product)
print(cost)
print(condition)

以下代码的结果:

['xbox 360', 'playstation 4', 'playstation 3', 'playstation 2']
['13000', '30000', '30000', '30000']
['new', 'new', 'old', 'old']

下面使用公共的zip(*...)转置模式,同时在适当的分隔符上拆分字符串:

>>> prd, cst, cnd = zip(*(s.split(' | ') for s in data))
>>> prd
('xbox 360', 'playstation 4', 'playstation 3', 'playstation 2')
>>> cst
('13000', '30000', '30000', '30000')
>>> cnd
('new', 'new', 'old', 'old')

相关问题 更多 >

    热门问题