用python进行判断单词,python检查单词是否在列表的某些元素中

I was wondering if there was a better way to put:

if word==wordList[0] or word==wordList[2] or word==wordList[3] or word==worldList[4]

解决方案

Very simple task, and so many ways to deal with it. Exciting! Here is what I think:

If you know for sure that wordList is small (else it might be too inefficient), then I recommend using this one:

b = word in (wordList[:1] + wordList[2:])

Otherwise I would probably go for this (still, it depends!):

b = word in (w for i, w in enumerate(wordList) if i != 1)

For example, if you want to ignore several indexes:

ignore = frozenset([5, 17])

b = word in (w for i, w in enumerate(wordList) if i not in ignore)

This is pythonic and it scales.

However, there are noteworthy alternatives:

### Constructing a tuple ad-hoc. Easy to read/understand, but doesn't scale.

# Note lack of index 1.

b = word in (wordList[0], wordList[2], wordList[3], wordList[4])

### Playing around with iterators. Scales, but rather hard to understand.

from itertools import chain, islice

b = word in chain(islice(wordList, None, 1), islice(wordList, 2, None))

### More efficient, if condition is to be evaluated many times in a loop.

from itertools import chain

words = frozenset(chain(wordList[:1], wordList[2:]))

b = word in words

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值