基于code计算值在Python阵列中创建新列 [英] Create new column in Python array based on values calculated in the code

查看:258
本文介绍了基于code计算值在Python阵列中创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有一个数组格式如下:ARR = [(1,1),(1,1)...(35,1),(35,1)])

Currently I have an array formatted like this: arr = [(1,1),(1,1)...(35,1),(35,1)])

我写了一个code,计算为阵,一次在每个有序对第3的值。我怎样才能创建一个存储在我的阵列中的每个计算的值作为新列的新列?

I've written a code that calculates a 3rd value for each ordered pair in the array, one at a time. How can I create a new column that stores each calculated value as a new column in my array?

推荐答案

元组是不可变的,所以你不能直接改变他们。幸运的是,你可以连接另一个元组给他们。假设你有一个数组:

Tuples are immutable, so you can't directly alter them. Fortunately, you can concatenate another tuple to them. Suppose you have an array:

arr = [(1, 2), (3, 4), (5, 6)]

和你想要一些整数追加到每一个元组,我们说的元组的改编的指标只是为了简单起见。也就是说,你想要的最终名单为:

and you want to append some integer to each tuple, let's say the index of the tuple in arr just for simplicity. That is, you want the final list to be:

arr = [(1, 2, 0), (3, 4, 1), (5, 6, 2)]

以下code将做到这一点:

The following code will do just that:

arr = [item + (a.index(item),) for item in arr]

请注意,在逗号和括号(a.index(项目),)是形成一个元组,而不是一个整数的关键。 (您只能串联元组其他元。)所以,如果你只是想一个号码添加到一个特定的元组,尝试:

Note that the comma and parentheses in (a.index(item),) are crucial to form a tuple instead of an integer. (You can only concatenate tuples to other tuples.) So if you just want to add a number to a specific tuple, try:

arr[0] += (3,)

这会 3 追加到第一个元素的末尾改编。这将允许你进行这样的拼接以任何环路产生第三点,你说发生一次。编码快乐!

which will append a 3 to the end of the first element in arr. That will allow you to perform such concatenation in whatever loop is generating the third point, which you say happens one at a time. Happy coding!

这篇关于基于code计算值在Python阵列中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆