使用python分隔存储在列表中的不同类型的内容

2024-10-02 22:26:14 发布

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

我有一份奥斯卡提名名单,格式如下。你知道吗

Birdman 2014    4   9    
The Grand Budapest Hotel    2014    4   9   
Whiplash    2014    3   5    

我要做的是把它们分成不同的类别:MovieYearoscarsnominations。你知道吗

我不能用空格来分隔它们,因为电影标题中有空格。请告诉我怎么做。你知道吗


Tags: the电影格式movie类别yearhotel空格
3条回答

我来试试这个:

#I assume the data is in 'text' as a string.
data = text.split()
Movie, Year, oscars, nominations = ''.join(data[:-3]), data[-3], data[-2], data[-1]

因此,考虑到数据在列表中,可以将其加载到for循环中:

# list_of_lines is a list where each item is a line of data
whole_data = list()
for text in line_of_lines:
    data = text.split()
    whole_data.append({'title':''.join(data[:-3]), 'year': data[-3], 'oscars': data[-2], 'nominations': data[-1]})
    # Do something with your info

你可以试着用python的字典。你知道吗

http://www.tutorialspoint.com/python/python_dictionary.htm

dict_var = {'title': 'Birdman', 'releasedate': 2014};

并访问它们:

dict_var['title'] == 'Birdman'
dict_var['releasedate'] == 2014

您可以简单地将电影条目拆分为以下四个字段:

str = "The Grand Budapest Hotel    2014    4   9   "
tmp = str.split()
[" ".join(tmp[0:len(tmp)-3])] + tmp[len(tmp)-3:len(tmp)]

相关问题 更多 >