![見出し画像](https://assets.st-note.com/production/uploads/images/10686179/rectangle_large_type_2_c57bde068b879e2461a543d64a337f1b.jpeg?width=800)
Photo by
tomekantyou1
[Python]filter関数で作る投票集計プログラム
1.投票集計プログラム
ランダムに生成した投票データを生成して投票の集計プログラムを作ります。引数に投票人数を渡します。
前回投稿したmap()で作る税込計算プログラムから派生して、そういえば似た関数にfilter()があることを思い出したのがきっかけになります。
公式ドキュメントより
https://docs.python.org/ja/3/library/functions.html#filter
filter(function, iterable)
iterable の要素のうち function が真を返すものでイテレータを構築します。iterable はシーケンスか、反復をサポートするコンテナか、イテレータです。function が None なら、恒等関数を仮定します。すなわち、iterable の偽である要素がすべて除去されます。
2.コード
from random import randint
from sys import argv
people_num = int(argv[1])
vote = [True, False]
#投票データ作成
votes = [vote[randint(0, 1)] for _ in range(people_num)]
#総投票数
total = len(votes)
#賛成
agree = len(list(filter(None, votes)))
#反対
disagree = total - agree
#投票率
voting_rate = round((agree / total) * 100, 2)
print("--投票結果--")
print(f"投票率:{voting_rate}%")
print(f"賛成:{agree} 反対:{disagree}")
3.実行結果
ython3 count_vote.py 100
--投票結果--
投票率:47.0%
賛成:47 反対:53
この記事が気に入ったらサポートをしてみませんか?