[英]Index into list in multiple places in Python?
Say I have two lists A which has 10 elements, and I want to assign the list B = [x1, y1]
to values in A. If the values are sequential, it is straightforward eg A[1:3] = B
. 假设我有两个包含10个元素的列表A,我想将列表
B = [x1, y1]
分配给A中的值。如果值是顺序的,则很简单,例如A[1:3] = B
But what if my indices are non-sequential? 但是,如果我的索引是非顺序的怎么办? In MATLAB I can do
A([3 10]) = B;
在MATLAB中,我可以做
A([3 10]) = B;
, is there an equivalently clean Python solution? ,是否有一个相当干净的Python解决方案? The for loop to do this is straightforward, but I am wondering if I am missing something more "Pythonic".
for循环很简单,但是我想知道是否缺少“ Pythonic”。
Slightly more verbose, but you can use tuple unpacking to assign to new indices: 稍微冗长一些,但是您可以使用元组拆包来分配给新索引:
>>> x = range(1, 11)
>>> x[3], x[7] = 99, 999
>>> x
[1, 2, 3, 99, 5, 6, 7, 999, 9, 10]
Whenever I try to emulate some Matlab functionality in Python I use numpy. 每当我尝试在Python中模拟某些Matlab功能时,我都会使用numpy。 Using a numpy
array
instead of a python list
allows to you get the functionality you are looking for with almost the same syntax as Matlab: 使用numpy
array
而不是python list
可以使您获得与Matlab几乎相同的语法的功能:
In [1]: import numpy as np
In [2]: a = np.arange(10)
In [3]: b = [200, 300]
In [4]: a[[2, 9]] = b
In [5]: a
Out[5]: array([ 0, 1, 200, 3, 4, 5, 6, 7, 8, 300])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.