LoginSignup
1
1

More than 3 years have passed since last update.

【Python】 リストの扱い方もろもろ

Last updated at Posted at 2019-08-07

競プロを始めてみて、頻出そうなリストの扱い方を自分用に整理しました。

文字列を一文字ずつ取って、リストにする。

コード

input_str = "101"
box = [num for num in input_str] # ここで、文字列をfor文で用いると、一文字ずつ取り出される。
print(box)

出力

['1', '0', '1']

※もう少し詳しく。
もう少し丁寧に書くと。

コード

for num in input_str:
    print(num)

出力

1
0
1

こうなる。要は文字列をforで取ると、一文字ずつ取り出される。

リスト中の、特定の要素数を求める。

コード

box = ['1', '0', '1']
one_count = box.count("1")
print(one_count)

出力

2

リストの順序を並び替える。

コード

numbers = [2, 5, 6, 1, 7, 23, 15, 19, 30, -4]
asce_numbers = sorted(numbers)
desc_numbers = sorted(numbers, reverse=True)

print(asce_numbers) #昇順
print(desc_numbers) #降順

出力

[-4, 1, 2, 5, 6, 7, 15, 19, 23, 30] #昇順
[30, 23, 19, 15, 7, 6, 5, 2, 1, -4] #降順
1
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1