LoginSignup
2
1

More than 3 years have passed since last update.

リストのn番目を取る。ただしリストがnより短い場合は一番最後を取る

Posted at

「リストのn番目を取る。ただしリストがnより短い場合は一番最後を取る」
(メソッド名にするならgetAtOrLast?)
というロジックが欲しい時の簡潔な実装について書きます。

愚直にやると、インデックスを1つずつ下げてループとか、
仕様でリストの長さが高々3とかに決まっている場合は決め打ちで1個1個見ていくのでもできますが、
あんまりキレイじゃないので別の方法を考えてみました。

別に特定の言語に寄らないので擬似コードで書くとこんな感じです。

擬似コード
リスト.最初のn個を取得().最後の要素を取得();

試しに何種類かの言語で書いてみます。

jsの場合
let list = ["a", "b", "c", "d", "e",];
console.log(list.slice(0, 3).slice(-1)[0])
// -> c

list = ["a", "b",]
console.log(list.slice(0, 3).slice(-1)[0])
// -> b
pythonの場合
list = ["a", "b", "c", "d", "e",]
print(list[:3][-1])
# -> c

list = ["a", "b",]
print(list[:3][-1])
# -> b
phpの場合
$list = ["a", "b", "c", "d", "e",];
echo array_slice(array_slice($list, 0, 3), -1)[0] . PHP_EOL;
# -> c

$list = ["a", "b",];
echo array_slice(array_slice($list, 0, 3), -1)[0] . PHP_EOL;
# -> b
phpの場合_LaravelのCollectionを使用できる場合
$list = ["a", "b", "c", "d", "e",];
echo collect($list)->take(3)->last() . PHP_EOL;
// -> c

$list = ["a", "b",];
echo collect($list)->take(3)->last() . PHP_EOL;
// -> b
2
1
0

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
2
1