簡體   English   中英

如何在某些列表項中應用邏輯運算符OR?

[英]How to apply logical operator OR in some of the list item?

我想知道是否可以在列表項中包含邏輯運算符OR。 例如:

CHARS = ['X','Y','Z']

將此代碼行更改為:(我知道這不是正確的方法)

誰能幫我?

CHARS = ['X','Y','Z','X OR Y','Y OR Z','X OR Z']

示例代碼:

import numpy as np

seqs = ["XYZXYZ","YZYZYZ"]

CHARS = ['X','Y','Z']
CHARS_COUNT = len(CHARS)

maxlen = max(map(len, seqs))
res = np.zeros((len(seqs), CHARS_COUNT * maxlen), dtype=np.uint8)

for si, seq in enumerate(seqs):
    seqlen = len(seq)
    arr = np.chararray((seqlen,), buffer=seq)
    for ii, char in enumerate(CHARS):
        res[si][ii*seqlen:(ii+1)*seqlen][arr == char] = 1

print res

它先掃描以檢測X是否發生,然后授予1,然后檢測Y,最后檢測Z。

輸出:

[[1 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 1]
 [0 0 0 0 0 0 1 0 1 0 1 0 0 1 0 1 0 1]]

包含邏輯或后的預期輸出:

[[1 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 1 1 1 0 1 1 0 0 1 1 0 1 1 1 0 1 1 0 1]
 [0 0 0 0 0 0 1 0 1 0 1 0 0 1 0 1 0 1 1 0 1 0 1 0 1 1 1 1 1 1 0 1 0 1 0 1]]

以下示例有些人為,但是使用itertools.combinations將是為給定列表生成大小為n的組合的一種方法。 將其與str.join()結合使用,您將能夠生成字符串,如問題的第一部分所示:

import itertools

CHARS = ['X','Y','Z']
allCombinations = [" OR ".join(x) for i in range(1,len(CHARS)) for x in itertools.combinations(CHARS, i)]

print repr(allCombinations)

輸出:

['X', 'Y', 'Z', 'X OR Y', 'X OR Z', 'Y OR Z']

暫無
暫無

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

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