2014年03月16日(日) [長年日記]
■ [python] Pythonでfind_index
ここ1週間くらいPythonのコードを書いている。メソッドでのself指定やprivateのアンダースコア始まりにまだ慣れない。バージョンが2.6と古めなのも辛い。
Rubyのfind_index相当のことをPythonで書く方法がなかなか分からなかったのでメモ。ジェネレータ式、組み込み関数のenumerate()とnext()を使って次のように書くのがいいみたい。
v = [(100, "c++"), (200, "python"), (300, "ruby")] print next((i for i, e in enumerate(v) if e[1] == "python"), None)
ちなみにRubyだと
v = [[100, "c++"], [200, "python"], [300, "ruby"]]
puts v.find_index {|e| e[1] == "python" }
C++なら
#include <algorithm>
#include <iostream>
#include <iterator>
#include <tuple>
#include <vector>
using namespace std;
int main() {
typedef tuple<int, string> i_s;
vector<i_s> v = {
make_tuple(100, "c++"),
make_tuple(200, "python"),
make_tuple(300, "ruby")};
auto it = find_if(
v.begin(),
v.end(),
[](const i_s& e) { return get<1>(e) == "python"; });
cout << (it == v.end() ? -1 : distance(v.begin(), it)) << endl;
}
かなあ。
[ツッコミを入れる]