辞書の値であるリストの値を変更したいと思います。 Pythonの方法でこれをコード化するとうまくいきませんが、リストの古典的なインデックスを使用するとうまくいきます。 私は何を意味するかを明確にするために、私は小さなデモを書きました。リスト内の4より小さいすべての値を1ずつ増やしたいと思います。dict値であるリストを変更する
A = [1, 2, 3, 4, 5]
x = {"a": [1, 2, 3, 4, 5]}
print("example 1, this works")
A = [a+1 if a < 4 else a for a in A]
print(A)
print("example 2, this not")
for v in x.values():
v = [a + 1 if a < 4 else a for a in v]
print(x)
print("example 3, this not either")
for v in x.values():
for a in v:
a = a+1 if a < 4 else a
print(x)
print("example 4, but this does")
for v in x.values():
for i in range(len(v)):
if v[i] < 4: v[i] += 1
print(x)
出力:
example 1, this works
[2, 3, 4, 4, 5]
example 2, this not
{'a': [1, 2, 3, 4, 5]}
example 3, this not either
{'a': [1, 2, 3, 4, 5]}
example 4, but this does
{'a': [2, 3, 4, 4, 5]}
2つのことが不可解されています 1.リストは、それが辞書の値であるか否かに応じて異なる方法で処理されます。 2.リスト値の変更は、適用するループ手法によって異なります。
私以外の理由はありますか? (可能性があります)はいの場合、それは何ですか?このコードで
あなたはhttp://nedbatchelder.com/text/names.htmlを読むべきです – chepner