正在提取元组的总值



我对Python很陌生,所以请原谅我的无知。我正试图计算一个系统中能量单位的总数。例如,这里的Omega将输出(0,0,0,1(和(2,2,2,1(以及大量其他元组。我想从Omega中提取有多少元组的总值为1(像第一个例子(,有多少元组总值为7(像第二个例子(。我该如何做到这一点?

import numpy as np
import matplotlib.pyplot as plt
from itertools import product
N = 4 ##The number of Oscillators
q = range(3) ## Range of number of possible energy units per oscillator

Omega = product(q, repeat = N)
print(list(product(q, repeat = N)))

试试这个:

Omega = product(q, repeat = N)
l = list(product(q, repeat = N))
l1 = [i for i in l if sum(i)==1]
l2 = [i for i in l if sum(i)==7]
print(l1,l2)

我相信您可以在元组以及整数/数字列表上使用sum()

现在你说omega是元组的列表,对吗?类似的东西

Omega = [(0,0,0,1), (2,2,2,1), ...)]

那样的话,我想你可以做

sums_to_1 = [int_tuple for int_tuple in omega if sum(int_tuple) == 1]

如果你想为不等于1的元组设置一些默认值,你可以把If语句放在列表理解的开头,然后进行

sums_to_1 = [int_tuple if sum(int_tuple) == 1 else 'SomeDefaultValue' for int_tuple in omega]

最新更新