简体   繁体   中英

Can I know what does this specific line of code means and how do i put it in a for loop in Python

I want to know what does this specific line means ? vowels = [i for i in string if i in m]

*The main code is : *

  def count_vowel(string):
    m = "AaEeIiOoUu"
    vowels = [i for i in string if i in m]
    if len(vowels) == 0:
        print("No vowels in the name")
    else:
        print(vowels)
        print("count:", len(vowels))

string = (input("enter anything to find amount of vowels in it :"))
count_vowel(string)

Can you please help me?

This is called a list comprehension . It builds a new list where each item takes on each of the characters in the string stored in the variable string , but a value is only produced if that character is also found in the string m .


The general structure for a list comprehension is:

resultingList = [operateOnIteratorsToProduceResult(i1, i2) for i1, i2 in iterable if condition] # lists are iterables

This can be seen as a conditional mapping, where we map the iterator(s) to a corresponding result if and only if the condition evaluates to True (otherwise no value is produced, and we continue iterating).

A special case (the one in your example), is where you simply produce the iterator. In that case, you are simply filtering the iterable on the condition:

resultingList = [i for i in iterable if condition]

There is also a full mapping like:

resultingList = [operateOnIteratorsToProduceResult(i1, i2) for i1, i2 in iterable if condition else alternativeResult]

where operateOnIteratorsToProduceResult(i1, i2) is produced as that element in the resulting list if the condition evaluates to True , otherwise alternativeResult is produced.

Best way to understand list comprehension is by separating out the parts.

It is equivalent to:

vowels = []
for i in string:
    if i in m:
        vowels.append(i)

It's a list comprehension , which iterates through the string and filters out all the values that are in the m string, and converts back into a string.

From the documentation:

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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