简体   繁体   中英

Print only the list items that contain a certain character

I'm trying to increment a count by one, if a string starts with a certain character and it repeats through a string. This is my code

def stringMatch(list1, char):
    count = 0
    for i in range(len(list1)):
        if char == list1[i][:]:
            count = count + 1 
            print(list1[i], count)

For the inputs list1 = ['cat', 'dog', 'corn'] and char = 'c'

The output should be

cat 1
corn 1 

In your code, you use if char == list1[i][:] . This causes your problem.

list1[i][:] is the same as list1[i] , which is really not what you're trying to do. You don't want to see if list1[i] is char ; rather, you want to know if list1[i] contains char . You could accomplish this in many ways. Here are three:

  1. char in list1[i]
  2. this for-loop:
found = False
for c in list1[i]:
    if c == char:
        found = True
        break
  1. if any(char==c for c in list1[i])

In any case, this is what I'd do:

def stringMatch(L, char):
    counts = (char in word for word in L)  # compute the counts of `char` in each list item
    for word, count in zip(L, counts):
        if not count: continue
        print(word, count)

Counting characters in a string is quite easy in python. There is a built in function for counting: string.count(char) . Your current method of counting does not work for two reasons.

  • The way you check if a letter is in a string does not work. Let's try a test case:

     >>>'c' == 'cat'[:] False 

    Using this method, you are essentially asking if 'c' is equal to the entire string, which is obviously wrong. A better way to do this would be using the in keyword. Let's try that with the previous example.

     >>>'c' in 'cat' True 

    So if we were to use this method, we would use the more pythonic in keyword. However,we won't need it.

  • Assuming that we use the above method (as I've stated above, we won't), there would still be an error in your output. According to your desired output, we are looking to count the characters in each word, yes? However, how you currently have it set up increments the total count variable each time that character is counted. So your output would be:

     cat 1 corn 2 

    This is an easy fix. We just have to move the variable inside the for loop so that it resets every time it increments. It would look something like this:

     for i in list1: total = 0 if char in i: total += 1 print(i, total) 

    However, even then, its not really an accurate loop because we want to count the characters in each word, correct? This (and your own method) only counts if the character exists in the word. Ironically, the in keyword doesn't occur in this solution. Instead we need to count each letter of each word to solve this. Here is your new code:

     for word in list1: total = 0 for letter in word: if letter == char: total += 1 print(word, total) 

Well, like I stated in the beginning, there is still an easier way. Using the string.count() function, the code is now four lines for the entire function. Note, I changed your function name. By convention camelCase is discouraged in python and lowercase/underscore is the convention. Be sure to read PEP 8, python's style-guide, to learn conventions. Anyways, here is your code:

    def string_match(list1, char):
        for i in list1:
            if i.count(char) > 0:
                print(i, i.count(char))

You just need use a string.count() .

>>> a = list1 = ['cat', 'dog', 'corn'] 
>>> a = { i:i.count('c') for i in list1 if i.count('c') > 0}
>>> for w in a:
...     print w, a[w]
...  
corn 1
cat 1

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