Py学习  »  Python

将Python列表字段一分为二,并将其保留在原位

CPhillips • 3 年前 • 1458 次点击  

如何在Python中拆分一个字段,然后将这两个字段并排保留在列表中?是否有使用旁白的命令 .split() ? 或者写一个函数来实现这一点更有意义吗?如何跨多个列表执行

性能不是主要问题。下面是我试图实现的一个例子。

编辑:我不介意使用 split() ,我只是想知道 怎样 这样的事情可以实现。

在格式化之前列出

['Intel', 'Core', 'i5-4210Y', '@', '1.50GHz', '(20%)', '998', 'N']

格式化后的列表

['Intel', 'Core', 'i5', '4210Y', '@', '1.50GHz', '(20%)', '998', 'N']
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130829
 
1458 次点击  
文章 [ 4 ]  |  最新文章 3 年前
Jacob
Reply   •   1 楼
Jacob    3 年前

我建议你做些类似的事情

string = '-'.join(list)
list = string.spit('-')

这在这里很管用,不过你也可以用 list.insert(item, index) 方法,如果这种方式导致问题。

Captain Caveman
Reply   •   2 楼
Captain Caveman    3 年前
specs = ['Intel', 'Core', 'i5-4210Y', '@', '1.50GHz', '(20%)', '998', 'N']

for i in specs:
    if i == 'i5-4210Y':
        specs.remove(i)
        i = i.split('-')
        specs.append(i[0])
        specs.append(i[1])

print(before)  
Chris
Reply   •   3 楼
Chris    3 年前

列出对救援的理解。

data = ['Intel', 'Core', 'i5-4210Y', '@', '1.50GHz', '(20%)', '998', 'N']
result = [y for x in data for y in x.split('-')]
# ['Intel', 'Core', 'i5', '4210Y', '@', '1.50GHz', '(20%)', '998', 'N']
Cubix48
Reply   •   4 楼
Cubix48    3 年前

下面是一种方法,使用列表理解和 split() :

data = ['Intel', 'Core', 'i5-4210Y', '@', '1.50GHz', '(20%)', '998', 'N']

new_data = [element for item in data for element in item.split("-")]
print(new_data)  # ['Intel', 'Core', 'i5', '4210Y', '@', '1.50GHz', '(20%)', '998', 'N']

for循环的等价物是:

new_data = []
for item in data:
    for element in item.split("-"):
        new_data.append(element)
print(new_data)  # ['Intel', 'Core', 'i5', '4210Y', '@', '1.50GHz', '(20%)', '998', 'N']