简体   繁体   English

在python的列表末尾插入元素?

[英]Insert an element at the end of a list in python?

I have an array 我有一个数组

[[1,2,3], [4,5,6], [7,8,9]]

I want to add 4th element at the end of each list as 我想在每个列表的末尾添加第四个元素

[[1,2,3,9], [4,5,6,36], [7,8,9,81]]

where inserted element is the square of last element. 其中插入元素是最后一个元素的平方。

How to do it? 怎么做?

This seems like a homework question, so I will not give you the code. 这似乎是一个家庭作业的问题,所以我不会给你的代码。

I will explain what you're supposed to do. 我将解释你应该做的事情。

What you have is a list of lists. 您所拥有的是列表列表。 Each element of a list can be iterated over like this: 列表的每个元素都可以像这样迭代:

>>> foo = [[1,2,3], [4,5,6], [7,8,9]]
>>> for element in foo:
...     print element

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

The last element of a list can be accessed by doing this: 通过执行以下操作可以访问列表的最后一个元素:

>>> foo = [1, 2, 3]
>>> print foo[-1]
3

And adding an element to the end of a list can be done like this: 可以将元素添加到列表的末尾,如下所示:

>>> foo = [1, 2, 3]
>>> foo.append(6)
>>> print foo
[1, 2, 3, 6]

Squaring a variable can be done with ** 可以使用**来平方变量

>>> a = 6
>>> print(a ** 2)
36

Rest is left to you to put together. 剩下的就交给你了。 When combining all these you can easily do the task. 将所有这些结合在一起时,您可以轻松地完成任务。

You can just go: 您可以去:

array = [[1,2,3,4]...]
for l in array:
    l.append(l[-1]**2)

You will end up just as you said. 您将按照您所说的结束。 Basically, it goes through your inner lists and gets the last item of the list and appends that item squared to the end of the list. 基本上,它遍历您的内部列表并获取列表的最后一项,并将该项目追加到列表的末尾。 I hope this helps. 我希望这有帮助。

You can use numpy as well. 您也可以使用numpy

import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
j=[pow(i[-1], 2) for i in a]
b = np.array(j)
np.column_stack((a,b))

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

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