2017-06-12 111 views
-4

我有这样一个列表的列表:访问元素通过索引

[ ['key1287', 'key5842', 'key3209','key5940', 'key42158', 'key43402', 'key31877', 'key51205', 'key2886'], 
    ['key41931', 'key41931', 'key41931', 'key41931'], 
    ['key453','key0090'], 
    ['key45333','key5432'], 
    ['key453313','key51432'] ] 

我如何可以访问由第一和第二索引的一个元素吗?

在此先感谢。

EDITED

假设我有许多列表的列表。未知名单中的长度。假设是30000.经过一些计算,我最终得到了我想要的列表中的30和31索引的元素(一个接一个)。此外,这些索引还未知。我在运行时知道他们。有人可以帮我弄这个吗?

再次感谢您。

+1

带*嵌套*'for'环... –

+0

你的意思是第一个2只列出了你的大名单呢? –

+2

'(在子列表[:2]中元素列表中的子列表元素)' –

回答

2

在所需位置分得一杯羹并chain结果:

def get_sublist_items(the_list, index=0, n=2): 
    return chain.from_iterable(the_list[index:index + n]) 
0
for key in listoflists[0]+listoflists[1]: 
    # do your magic 
0

我推荐使用链:

from itertools import chain 
superlist = [["a", "b"], ["c", "d"], ["e", "f"]] 
for element in chain(superlist[0], superlist[1]): 
    print(element) 
# or 
for element in chain.from_iterable(superlist[0:2]) 
    print(element) 

他们都输出:

a 
b 
c 
d 

链遍历第一个列表中,直到完成,然后用下面等开始。 这是非常有效的,因为不需要创建一个新的列表,这个列表是你想要迭代的列表的总和。

更新:

如果指标可能会有所不同,你可以做到以下几点:

def get_sublist(superlist, index, n): 
    return chain.from_iterable(superlist[index:index + n]) 

for element in get_sublist(superlist, 30, 2): 
    print(element) 
0

你想要的子列表的第一个和第二个元素是对的?

your_list = [ ['key1287', 'key5842', 'key3209','key5940', 'key42158', 'key43402', 'key31877', 'key51205', 'key2886'], 
    ['key41931', 'key41931', 'key41931', 'key41931'], 
    ['key453','key0090'], 
    ['key45333','key5432'], 
    ['key453313','key51432'] ] 
s=[(sublist[0],sublist[1]) for sublist in your_list] 

print(s) 

输出:

[('key1287', 'key5842'), ('key41931', 'key41931'), ('key453', 'key0090'), ('key45333', 'key5432'), ('key453313', 'key51432')]