簡體   English   中英

提取元組的總值

[英]Extracting total value of a tuple

我對 Python 很陌生,所以請原諒我的無知。 我正在嘗試計算系統中的能量單位總數。 例如,這里的 Omega 將 output 和 (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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM