列表中元素的概率

2024-10-06 13:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据

List = [[[12,1,6],[12,1,6],15],[[12,2,6],[12,2,6],18]],[[12,3,6],[12,3,6],24]]

我有一个包含

number of rows having a transition from 12,1,6 to 12,1,6 is 15
number of rows having a transition from 12,2,6 to 12,2,6 is 18
number of rows having a transition from 12,3,6 to 12,3,6 is 24

作为列表 此数据不是生成的。我的数据中还有许多其他可能的组合。上面所说的就是示例

我希望我的输出是一个具有此转换概率的列表

比如说


P1 = the probability of transition from 12,1,6 to 12,1,6 
   = 15/total length of rows/elements  in the list.(In this case it is 3)

P2 = the probability of transition from 12,2,6 to 12,2,6 
   = 18/total length of rows in the list

我的输出需要

List =[[[12,1,6],[12,1,6],15,P1=(15/3)*100],[[12,2,6],[12,2,6],18,P2]],[[12,3,6],[12,3,6],24,P3]]

我已经尝试了很多,如果我得到建议会很有帮助

def Sort(sub_li):
   sub_li.sort(reverse = True, key = lambda x: x[1])
   return sub_li

print(Sort())

Tags: oftheto数据fromnumber列表is
1条回答
网友
1楼 · 发布于 2024-10-06 13:31:04

List18之后有一个额外的],所以我在编写这段代码之前删除了它,这段代码假定所有行的长度都相同

List = [[[12,1,6],[12,1,6],15],[[12,2,6],[12,2,6],18],[[12,3,6],[12,3,6],24]]

for i, value in enumerate(List):
    value.append(("P%d=%f" % ((i + 1), value[2] / len(value[0]) * 100)))

print(List)

输出:

[[[12, 1, 6], [12, 1, 6], 15, 'P1=500.000000'], [[12, 2, 6], [12, 2, 6], 18, 'P2=600.000000'], [[12, 3, 6], [12, 3, 6], 24, 'P3=800.000000']]

相关问题 更多 >