Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
インデックスを使用してリストを反転または反復するにはどうすればよいですか?
これが例です
lst = [3,2,4,1,5]
出力は次のようになります:([3,2,4,5,1]最後に1であるインデックス3が配置されます)
[3,2,4,5,1]
もう一つの例:
lst = [1,5,4,2,3]
出力:([1,5,4,3,2]最後に2であるインデックス3が配置されます)
[1,5,4,3,2]
スライスを使ってリストを逆にしたようなものです。
リストの一部を特定のポイントを超えて反転させたい場合、最も簡単な方法は次のとおりです。
output = (lst[:3] # take the list before element 3 + # and add lst[3:] # the list from element 3 on [::-1] # reversed )
または、コメントなし:
output = lst[:3] + lst[3:][::-1]
既存のリストを変更する場合は、次のことができます。
lst[3:] = lst[3:][::-1]