代码

python访问列表元素可以根据单个索引访问,可以使用切片访问连续的元素,但是当想访问列表的多个不连续的元素时,可以建立一个索引列表,然后使用如下的列表推导式。

list_1 = [1,2,3,4,5]
list_2 = [2,4]
list_3 = [list_1[i] for i in list_2]

或者使用 .index()函数

list_1 = [1,2,3,4,5]
list_2 = [2,4]
list_3 = [x for x in list_1 if list_1.index(x) in list_2]

相关文章:

  • 2022-12-23
  • 2021-08-04
  • 2022-12-23
  • 2022-12-23
  • 2021-06-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案