Блог пользователя technical_guru

Автор technical_guru, 5 лет назад, По-английски

Let's assume, you have a seq. of strings such as,

# List of string 
list_of_strings = ['Sonia' , 'limo', 'karl', 'jhon', 'john', 'shawn']

Now, we'll check if the input list contains a string element 'john'.

Check if the list has the element — using python IN Operator

# check if the list has the element using 'in'
if 'john' in list_of_strings :
    print("Yes, 'john' found in List:", list_of_strings)

if 'walter' not in list_of_strings :
    print("Yes, 'walter' NOT found in List: " , list_of_strings)

Check if the list has the element — using list.count()

# check if the list has the element using list.count()
if list_of_strings.count('john') > 0 :
    print("Yes, 'john' found in List : " , list_of_strings)

Check if the list has the element — using list comprehension

# check if the list has the element using list comprehension
res = [x for x in list_of_strings if x == 'john']
if res:
   print("Yes, '{}' found in List: {}".format(res[0], list_of_strings))

Ref:- 1) What is a list in Python 2) Python list comprehension

  • Проголосовать: нравится
  • -19
  • Проголосовать: не нравится