Python从列表中删除数据以添加到新列表中

时间:2013-03-28 21:13:49

标签: python list word add

问题:如何从列表中删除第一个单词以添加到名为car_list的新列表中,并将其余单词添加到另一个列表other_list中。

other_list中,我将其余部分放入字典中

例如,当我读到文件时,我会得到类似

的内容

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

car_list = [] other_list = []

如何获得结果

car_list = [Overland, Scripps-Booth, Briggs]

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

以下是我的内容

data_file = open("facts.txt", 'r')


def clean_list(data_file):
    new_list =[]
    clean_list =[]
    car_list = []
    other_list = []
    D = {}
    for i in data_file:
        new_list = data_file.split('\n') #change split by new line or word

    clean_list = [(x.strip(' ')) for x in new_list]
    car_list = (clean_list.strip().split(' ')[2:], ' ') 
    other_list = dict(zip(keys, values))# Just an example
    return car_list

car_list = clean_list(data_file)

我想car_list = (clean_list.strip().split(' ')[2:], ' ')

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

car_list = (clean_list.lstrip().split(' ')[2:], ' ')

AttributeError: 'list' object has no attribute 'split'

AttributeError: 'list' object has no attribute 'lstrip'

我认为通过拼接可以工作,但没有骰子。

我尝试了car_list = clean_list.split(' ',2)[2]并且没有打印任何内容

任何想法?我知道该文件正在被阅读,但我不知道该怎么做。

3 个答案:

答案 0 :(得分:5)

我警告你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']

答案 1 :(得分:1)

最终你也可以使用正则表达式来分割字符串。

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']

答案 2 :(得分:1)

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

<强>输出

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