Python: 二値の交換

Sponsored Link

このエントリーをはてなブックマークに追加
はてなブックマーク - Python: 二値の交換
Bookmark this on Delicious
Share on LinkedIn
Bookmark this on Livedoor Clip
Bookmark this on Yahoo Bookmark

ソート系のアルゴリズムを実装する際などに、配列の任意の2つの要素を交換する処理が必要な場合がありますので、以下にその手順の一例を示します。

ソースコード

# coding: UTF-8

a = [10, 20]
print '%d %d' % (a[0], a[1])
a[0], a[1] = a[1], a[0]
print '%d %d' % (a[0], a[1])

実行結果

10 20
20 10

何だかperlの多重代入を思い出します。

関連すると思われる記事:

Sponsored Link

This entry was posted in Python and tagged , . Bookmark the permalink.

Facebook comments:

2 Responses to Python: 二値の交換

  1. Pingback: Kazuaki Morihisa

  2. Pingback: わかめにゅーす(Python)

コメントを残す

メールアドレスが公開されることはありません。

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>