2024-04-27 00:23:58 发布
网友
我有一个对象列表list和一个索引列表indexes,我想创建一个new_list包含在这个索引列表定义的索引处的原始列表的对象。 我试过几种方法,但都做不到。 例如,如果indexes列表中只有2个索引,那么为什么下面的方法不起作用?new_list = [list[indexes[0]] + list[indexes[1]]] 将很高兴知道解决这个问题的一般方法,为任何长度的索引列表。你知道吗
list
indexes
new_list
new_list = [list[indexes[0]] + list[indexes[1]]]
以下工作:
my_list=['a','b','c','d'] my_indices=[1, 3] new_list = [my_list[i] for i in my_indices if i < len(my_list)]
上面的列表理解将在my_indices中的索引处获得my_list的所有元素。存在if,这样就不会出现IndexError: list index out of range错误。你知道吗
my_indices
my_list
if
IndexError: list index out of range
您的问题是您使用了+操作符,它连接您的对象:
+
>>> [my_list[my_indices[0]] + my_list[my_indices[1]]] ['bd']
以下工作:
上面的列表理解将在
my_indices
中的索引处获得my_list
的所有元素。存在if
,这样就不会出现IndexError: list index out of range
错误。你知道吗您的问题是您使用了
+
操作符,它连接您的对象:相关问题 更多 >
编程相关推荐