PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] How to print out list one single time after append?

 May 13, 2022     append, list, python, python-3.x     No comments   

Issue

list = ('S', 'S', 'C', 'R', 'C', 'R', 'S', 'C', 'C', 'R', 'S', 'C', 'S', 'S', 'R', 'C', 'R', 'C', 'C', 'S', 'R')
list1 = []
for i in list:
    if i == 'C':
        list1.append('C')
        print(list1)

So I was trying to create a empty list and add only 'C' into list1. And calculate how many 'C' are in the list1. Iteration of over the list and len(list1) but that would give me all the len of my iteration... what are easier ways of calculating numbers of only'C' in list1? without iteration? Thanks in advance.


Solution

You have many ways to solve this:

classical loop

my_list = ('S', 'S', 'C', 'R', 'C', 'R', 'S', 'C', 'C', 'R', 'S', 'C', 'S', 'S', 'R', 'C', 'R', 'C', 'C', 'S', 'R')

i = 0
for letter in my_list:
    if letter == 'C':
        i+=1
print(i)

list comprehension

>>> len([None for i in my_list if i == 'C'])
8

filter

NB. this might be most useful to count not strictly identical objects

>>> len(list(filter('C'.__eq__, my_list)))
8

collections.Counter

(already proposed by @eduardosufan)

from collections import Counter
Counter(my_list)['C']

output: 8

list.count method

>>> my_list.count('C')
8


Answered By - mozway
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing