按索引访问列表中的元素

2024-04-19 04:48:00 发布

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

我有一个列表,比如:

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

如何逐个访问第一个和第二个索引中的元素?你知道吗

提前谢谢。你知道吗

编辑

假设我有一个包含许多列表的列表。名单的长度不详。假设三万。经过一番计算,我最终决定,我要采取的元素(一个接一个)的30和31指数的名单。此外,这些索引也不得而知。我在运行时就知道了。有人能帮我吗?你知道吗

再次感谢你。你知道吗


Tags: 元素列表名单key5940key453key5842key31877key2886
3条回答

你想要子列表的第一个和第二个元素,对吗?你知道吗

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')]
for key in listoflists[0]+listoflists[1]:
   # do your magic

在所需位置切一片chain结果:

def get_sublist_items(the_list, index=0, n=2):
    return chain.from_iterable(the_list[index:index + n])

相关问题 更多 >