Python从列表中删除要添加到新lis中的数据

2024-09-25 00:32:29 发布

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

问题:如何从列表中删除第一个单词,以添加到名为^{{cd1>}的新列表中,并保留其余的添加到另一个列表^{{cd2>}。

在^{cd2>}中,我将把其余的放进字典中

比如我读文件时,我得到了

^{cd4>}

^{cd5>} other_list = []

如何获得如下结果

car_list = [Overland, Scripps-Booth, Briggs]

other_list = [1911,OctoAuto, 1913, Bi-Autogo, 1920, and Stratton flyer]

以下是我所拥有的

^{pr2}$

我想^{cd7>}

会起作用的,但我得到以下错误。

^{pr3}$

^{cd8>}

^{cd9>}

我以为剪接会奏效,但不会有骰子

我试过^{cd10>}但没有打印任何内容

有什么想法吗?我知道文件正在被读取,但我只是不知道该怎么做。


Tags: 文件列表字典单词carlistothercd1
3条回答

最后,还可以使用regex来分割字符串。在

import re
data_file = ['1911 Overland OctoAuto', 
             '1913 Scripps-Booth Bi-Autogo',
             '1920 Briggs and Stratton Flyer']

car_list = []
other_list = []
delimiter_space = re.compile(' ')
for entry in data_file:
    year, make, model = delimiter_space.split(entry,maxsplit=2)
    car_list.append(make)
    other_list.append(year)
    other_list.append(model)

print car_list
>>>> ['Overland', 'Scripps-Booth', 'Briggs']
print other_list
>>>> ['1911', 'OctoAuto', '1913', 'Bi-Autogo', '1920', 'and Stratton Flyer']
T = [x.split(' ', 2) for x in data_file]
car_list = [ x[1] for x in T]
other_list =  [ v for x in T for v in x if v != x[1]]
print car_list
print other_list

输出

^{pr2}$

我警告您,other_list看起来像是不同类型数据的混合体。那通常是不明智的。有了这个免责声明,下面是一个尝试:

data_file = ['1911 Overland OctoAuto', 
             '1913 Scripps-Booth Bi-Autogo',
             '1920 Briggs and Stratton Flyer']

car_list = []
other_list = []
for entry in data_file:
    year, make, model = entry.split(' ',2)
    car_list.append(make)
    other_list.append(year)
    other_list.append(model)

print car_list
>>>> ['Overland', 'Scripps-Booth', 'Briggs']
print other_list
>>>> ['1911', 'OctoAuto', '1913', 'Bi-Autogo', '1920', 'and Stratton Flyer']

相关问题 更多 >