循环浏览大量列表,仅将某些元素存储到新列表中

时间:2019-02-28 16:38:41

标签: python json itertools

我有一个列表,其中包含165个电影标题和信息(来自json文件):

results = 
['tt0758758',
 'Into the Wild',
 '2007',
 'Emile Hirsch',
 ' Marcia Gay Harden',
 ' William Hurt',
 ' Jena Malone',
 '',
 'Based on a true story. After graduating from Emory University',
 ' Christopher McCandless abandoned his possessions',
 ' gave his entire savings account to charity',
 ' and hitchhiked to Alaska to live in the wilderness. Along the way',
 ' Christopher encounters a series of characters who shape his life.',
 'Sean Penn',
 '8.1',
 '516',
 '973']

我只想存储选定的值

tt0758758 Into the Wild , ['Sean Penn', '8.1', '516', '973']

到另一个列表results_add= []。 请注意,条目的元素大小不同。

我尝试过:

results_add = []
for i in range(len(results)-1):
    results_add = (results[i+1][0],results[i+1][1],results[i+1][-4:])
    print(results_add)

这会打印整个列表,但只会将最后一个值(标题)存储到我新创建的列表中

len(results_add)
3

2 个答案:

答案 0 :(得分:1)

您要追加到results_add列表中。正如您当前的代码一样,它只会在每次迭代后覆盖:

results_add = []
for i in range(len(results)-1):
    temp = (results[i+1][0],results[i+1][1],results[i+1][-4:])
    results_add.append(temp)
print(results_add)

答案 1 :(得分:0)

for i in range(len(results)-1):
    results_add = (results[i+1][0],results[i+1][1],results[i+1][-4:])

每次循环,您都要重新分配results_add,它会丢失其先前的内容。