简体   繁体   English

Python快捷方式来填充列表

[英]Python short cut to fill list

Java has Arrays.fill(A,1) . Java具有Arrays.fill(A,1) For a pre-existing List A , is there a shortcut for filling the list with 1 ? 对于预先存在的列表A ,是否存在用1填充列表的快捷方式? I am writing a function that takes an array and changes the array in some ways. 我正在编写一个接受数组并以某种方式更改数组的函数。 Since arrays are pointers, my function will not return an array. 由于数组是指针,因此我的函数不会返回数组。 The caller will see the changes after my function returns. 函数返回后,调用方将看到更改。 The first step in my function is to fill the array with 1s . 我函数的第一步是用1s填充数组。 Doing

def my_work(A):
   A =[1]*len(A) 
   # more work on A

does not seem to change A when my_work is done. my_work完成后,似乎没有更改A

So is my only option 所以我唯一的选择

for i in range(len(A)):
  A[i]=1

or is there a shortcut? 还是有捷径? Mine looks like a workaround. 我的看起来像一个解决方法。

If you really want to change A in place, the A[:] syntax should work: 如果您确实想更改A ,则A[:]语法应该起作用:

>>> A = [1,2,3]
>>> def my_work(A):
...     A[:] = [1]*len(A) 
...     
>>> A
[1, 2, 3]
>>> my_work(A)
>>> A
[1, 1, 1]

And here is the relevant section of the tutorial ("assignment to slices"). 是本教程的相关部分(“切片分配”)。

A is not changing because your not returning it our of my_work . A不会更改,因为您未将my_work返回它。 Once my_work is complete the A you have in there is not referenced. 一旦my_work完成,将不引用您所在的A。

def my_work(A):
    A =[1]*len(A) 
    return A  #This line is needed

A = my_work(A)

Another way to do this is something like this. 这样做的另一种方法是这样的。

def reset_list(L, x):
     return [x for i in xrange(len(L))]

A = reset_list(A,1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM