简体   繁体   English

在一行中将值添加到数组

[英]Add values to array in one line

How can I write this code in one-line? 如何单行编写此代码?

aa = []
for s in complete:
    aa.append(s)

I know there are several solutions. 我知道有几种解决方案。 I would really appreciate if you could write them down. 如果您能写下来,我将不胜感激。 Thanks! 谢谢!

like this (be care with strings): 像这样(注意字符串):

aa.extend(complete)

or with list comprehension: 或具有列表理解功能:

aa = list(s for s in complete)

or if u want to copy list u can do follow: 或者,如果您想复制列表,则可以执行以下操作:

aa = complete[:]
aa = complete.copy() # same
aa = list(complete) # same

or just use '+': 或只使用'+':

aa += complete

只要您需要将aa设置为complete ,就可以使用

aa = complete

列表理解很棒:

aa = [s for s in complete]

If you want to add values to array in one line, it depends how the values are given. 如果要在一行中将值添加到数组,则取决于如何给出值。 If you have another list , you can also use extend: 如果还有另一个list ,也可以使用extend:

my_list = []
my_list.extend([1,2,3,4])

To extend aa , use the extend() function: 要扩展aa ,请使用extend()函数:

aa.extend(s for s in complete)

or 要么

aa.extend(complete)

If you simply wanted to equate the two, a simple = is fine: 如果您只是想将两者相等,则简单的=就可以了:

aa = complete

I like to do such things with a list comprehension: 我喜欢用列表理解来做这些事情:

aa = [s for s in complete]

Though, depending on the type of complete , and whether or not you want to use package like numpy there may be a faster way, such as 不过,根据complete类型,以及是否要使用numpy之类的软件包,可能会有更快的方法,例如

import numpy as np
aa = np.array(complete)

I'm sure there are many other ways as well :) 我敢肯定还有很多其他方法:)

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

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