【问题标题】:How to apply logical operator OR in some of the list item?如何在某些列表项中应用逻辑运算符 OR?
【发布时间】:2015-12-15 03:21:31
【问题描述】:

我想知道是否可以在列表项中包含逻辑运算符 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]]

【问题讨论】:

    标签: python arrays list numpy logical-operators


    【解决方案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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      相关资源
      最近更新 更多