简体   繁体   English

我怎样才能对 if/elif 进行理解,而不是其他?

[英]How can I do a for comprehension with if/elif, and no else?

I want to create a comprehension for from this:我想从中创建一个理解:

for w in s:
    if w in pw_set:
        a[w] += 1
    elif t in nw_set:
        a[w] += 1

I have something like this but it doesn't work我有这样的东西,但它不起作用

[(a[w]+=1) if (w in pw_set) else (a[w]+=1) if (w in nw_set) for w in s]

If you really, absolutely want to do that with a list comprehension, you'll need a collections.Counter to accumulate the results into.如果你真的,绝对想用列表理解来做到这一点,你需要一个collections.Counter来累积结果。 (It can count occurrences from a flat list of values.) (它可以从一个简单的值列表中计算出现次数。)

> pw_set = {'a','b', 'c'}
> nw_set = {}
> s = ['a', 'b', 'q', 'z', 'e']
> a = collections.Counter(
    [
        w
        for w in (
            w if (w in pw_set or w in nw_set) else None
            for w in s
        )
        if w is not None
    ]
)
Counter({'a': 1, 'b': 1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM