0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

文系学生のプログラミング学習9日目ーPythonのリストー

Last updated at Posted at 2019-07-31

今日はPythonでリストの学習をしました。リストについてはscratchで学習していたので、とっつきやすかったです。違いはindexだけですかね。Scratchではリストのはじめが1なのですが、Pythonは0が最初です。

リストの最初の奇数をリストの最後尾に移す

タイトルのとおりです。すべての奇数ではなく、1番最初だけです。

def push_first_odd_back(lst):
    for i in range(0, len(lst)):
        if lst[i] % 2 == 0:
            pass
        else:
            item = lst[i]
            lst.pop(i)
            lst.append(item)
            break

.pop()は()内にindexを入れるのに対し、.append()はitemを入れるので、item = lst[I] としてから、.pop(),.append()としました。
何もしないとループしてしまい、すべての奇数に対してfunctionしてしまうのでbreakでスクリプトを終了させました

リスト内のリストを1つのリストに結合する

例えば、
list = [[1,2,3], [4,5], [6,7]]というようにリストのなかにあるリストを1つに結合して、
new_list = [1,2,3,4,5,6,7] とするコードを書きます。

def flatten(lst):
    x = []
    for item in lst:
        x.extend(item)
    return(x)

.extend()を使って新たなリストxにitemを追加します。

データを扱う上でリストを扱えるかは重要になると思うので、さらに勉強します。

終わり

0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?