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

标签 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' 对象没有属性 'split'

AttributeError: 'list' 对象没有属性 'lstrip'

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

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

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

最佳答案

我要警告您的是,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']

关于Python 从列表中删除数据以添加到新列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15692293/

相关文章:

python - Hindmarsh-Rose 模型的相空间轨迹

python - Canopy 获取 shell 中的文件列表

python - 计算用作字典值的列表中的项目

c# - 在 Asp.net c# 中使用 linq 对 list<object> 进行升序和降序排序

C++ 结构列表 push_back 的问题

python - 查找文件中单词的出现

python - 如何将时间戳字符串转换为日期时间对象?

Python 求和文件中的频率

php - PHP替换字符串中的随机词

python - 计算嵌套列表中的频率