文字列を取得して、既に存在する別の文字列の代わりにリストに挿入するにはどうすればよいですか (範囲外エラーが発生しないようにします)。
例:
l = ["rock", "sand", "dirt"]
l.remove[1]
l.insert(1, "grass")
これよりも簡単な方法はありますか?空のリストがあり、順序が重要な場合はどうすればよいですか?
あなたに必要なのは:
>>> l = ["rock", "sand", "dirt"]
>>> l[1] = "grass"
>>> l
['rock', 'grass', 'dirt']
>>>
リストは、Python での直接置換をサポートしてlist[index] = value
います。
要素を直接置き換えることもできます:l[1] = 'grass'
任意のリストを見ている場合、アイテムがリストにあるかどうか、またはそれがどのインデックスであるかがわからない場合があります。最初にアイテムがリストにあることを確認してから、インデックスを探して、それを置き換えることができます。次の例では、置換対象と一致するリスト内のすべての要素に対してこれを行います。
def replace_list_item(old, new, l):
'''
Given a list with an old and new element, replace all elements
that match the old element with the new element, and return the list.
e.g. replace_list_item('foo', 'bar', ['foo', 'baz', 'foo'])
=> ['bar', 'baz', 'bar']
'''
while old in l: # check for old item, otherwise index gives a value error
index = l.index(old)
l[index] = new
return l
それから:
l = ["rock", "sand", "dirt", "sand"]
replace_list_item('sand', 'grass', l)
戻り値:
['rock', 'grass', 'dirt', 'grass']