[英]python conditional access to list of lists
I would like some suggestion on a problem concerning the access of data stored in a list of lists. 我想就存储在列表列表中的数据访问问题提出一些建议。
My list of lists looks like this: 我的列表列表如下所示:
my_list = [['RN1', 200, 0.55], ['RN2', 0.8, 0.44], ['RN3', 0.2, 0.01]]
The list is ordered with respect of the third element of the inner lists. 该列表是根据内部列表的第三个元素排序的。
What I want to do is: 我想做的是:
To check if the third element of the first inner list is greater or equal to 0.9; 检查第一个内部列表的第三个元素是否大于或等于0.9; if yes, i want to create a list containing the first 2 elements of the first inner list 如果是,我想创建一个包含第一个内部列表的前2个元素的列表
my_list[0][2] >= 0.9
Which if true would give: 如果是真的会给出:
new_list = [['RN1', 200]]
If not, I want to add to my_list[0][2]
element the corresponding element of the second inner list: 如果没有,我想在my_list[0][2]
元素中添加第二个内部列表的对应元素:
my_list[0][2] + my_list[1][2]
and check if this value is greater 0.9
. my_list[0][2] + my_list[1][2]
并检查此值是否大于0.9
。
If yes I want to stop the loop adding to my new_list the first 2 elements of the second inner list: 如果是,我想停止循环添加到我的new_list第二个内部列表的前2个元素:
new_list = [['RN1', 200], ['RN2', 0.8]]
If not continue adding elements till the threshold of 0.9
is reached. 如果没有继续添加元素,直到达到阈值0.9
。
Of course this is just an example. 当然这只是一个例子。 My real lists can be a lot bigger and the process should be iterative. 我的真实列表可以更大,过程应该是迭代的。
I have tried different possibilities but all of them are not working. 我尝试了不同的可能性,但所有这些都没有用。 For example I have done: 例如,我做了:
sum_percentage = 0.0
new_list =[]
for i in old_list:
if sum_percentage <= 0.9:
sum_percentage = sum_percentage + i[2]
new_list.append([i[0], i[1]])
And other variants of this...Now I am stuck. 和其他变种......现在我被卡住了。
Any tips? 有小费吗?
Thanks a lot 非常感谢
This'll do the job for you: 这将为你做的工作:
sum_percentage = 0.0
new_list = []
for i in old_list:
new_list.append(i[:2])
sum_percentage += i[2]
if sum_percentage >= 0.9:
break
I think it's self-explanatory, but if you're confused about anything, let me know and I'll expand this answer. 我认为这是不言自明的,但如果你对任何事情感到困惑,请告诉我,我会扩展这个答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.