简体   繁体   English

Python列表元素语法

[英]Python list element syntax

I'm new to python and I want to use the syntax 我是python的新手,我想使用语法

a = [3, 6]
for x in a:
    x *= 2

so 'a' would be [6, 12] 因此“ a”为[6,12]

...but this doesn't seem to work. ...但这似乎不起作用。 How should I write the code, as simple as possible, to get the wanted effect? 我应该如何尽可能简单地编写代码以获得所需的效果?

The following code 以下代码 change 更改 creates a new int object and rebinds x , and not changes the items of the list. 创建一个新的int对象并重新绑定x ,而不更改列表的项目。

for x in a:
    x *= 2

To change the item of the list you should use a[..] = .. . 要更改列表的项目,应使用a[..] = ..

for i in range(len(a)):
    a[i] *= 2

You can also use List comprehension as the answer of @Hyperboreus. 您也可以使用列表理解作为@Hyperboreus的答案。

To change the value of the nested list, use nested loop. 要更改嵌套列表的值,请使用嵌套循环。

for i in range(len(a)):
    for j in range(len(a[i]):
        a[i][j] *= 2

Alternative that use enumerate . 使用enumerate替代方法。

for i, x in enumerate(a):
    a[i] = x * 2

You can use this: 您可以使用此:

a = [x * 2 for x in a]

And for a nested list: 对于嵌套列表:

a = [ [1,2,3], [4,5,6] ]
a = [ [x * 2 for x in x] for x in a]

You can use either list comprehension or map() function. 您可以使用列表推导map()函数。

my_list = [3, 6]
my_list = [x * 2 for x in my_list]

my_list = [3, 6]
my_list = map(lambda x: x * 2, my_list)

If you find you need to do a lot of these things, maybe you should use numpy 如果您发现需要做很多这样的事情,也许您应该使用numpy

>>> import numpy as np
>>> a = np.array([3, 6])
>>> a *= 2
>>> a
array([ 6, 12])

2 (or more) dimensional array works the same 2个(或更多)维数组的作用相同

>>> a = np.array([[3, 6],[4,5]])
>>> a *= 2
>>> a
array([[ 6, 12],
       [ 8, 10]])

But there is an overhead converting between list and numpy.array , so it's only worthwhile (efficiency wise) if you need to do multiple operations. 但是listnumpy.array之间有一个开销转换,因此只有在需要执行多个操作时才值得(在效率方面)。

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

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