Python checks if a word is in specific list items

I was wondering if there is a better way:

if word==wordList[0] or word==wordList[2] or word==wordList[3] or word==worldList[4] 
+4
source share
3 answers

A very simple task and so many ways to handle it. Exciting! That's what I think:

If you know for sure that the wordList is small (otherwise it may be too inefficient), I recommend using it:

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

Otherwise, I will probably go after this (it all the same depends!):

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

For example, if you want to ignore multiple indexes:

 ignore = frozenset([5, 17]) b = word in (w for i, w in enumerate(wordList) if i not in ignore) 

It is pythonic and scalable.


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 
+6
source
 word in wordList 

Or, if you want to check 4 first,

 word in wordList[:4] 
+7
source

IndexList has a list of pointers that you want to check (ie [0,2,3] ), and wordList has all the words you want to check. Then the following command will return the 0th, 2nd and 3rd wordList elements as a list:

 [wordList[i] for i in indexList] 

This will return [wordList[0], wordList[2], wordList[3]] .

+1
source

Source: https://habr.com/ru/post/1400902/


All Articles