返された 2 つのリストを次のような 2 つの異なるリストに追加したいと考えています。
def func():
return [1, 2, 3], [4, 5, 6]
list1.append(), list2.append() = func()
何か案は?
最初に戻り値をキャプチャしてから、次を追加する必要があります。
res1, res2 = func()
list1.append(res1)
list2.append(res2)
list.extend()
ここでリストを返しているようですが、代わりに使用するつもりはありませんか?
list1
とを拡張する場合はlist2
、スライスの割り当てを使用できます。
list1[len(list1):], list2[len(list2):] = func()
しかし、これは a) 初心者にとっては驚くべきことであり、b) 私の意見ではかなり読みにくいものです。私はまだ別の割り当てを使用してから、呼び出しを拡張します。
res1, res2 = func()
list1.extend(res1)
list2.extend(res2)
戻り値を保存するだけではないのはなぜですか?
a, b = func() #Here we store it in a and b
list1.append(a) #append the first result to a
list2.append(b) #append the second one to b
これで、以前だった場合とa
以前だった場合、次の結果が得られます。[10]
b
[20]
>>> a, b
[10, [1,2,3]], [20,[4,5,6]]
いや、難しくなかったですよね?
ところで、おそらくリストをマージしたいと思うでしょう。これには、次を使用できますextend
。
list1.extend(a)
それが役に立てば幸い!
1 行で解決することはできません (不可解なハックを使用しない限り、これは常に悪い考えです)。
あなたが得ることができる最高のものは次のとおりです。
>>> list1 = []
>>> list2 = []
>>> def func():
... return [1, 2, 3], [4, 5, 6]
...
>>> a,b = func() # Get the return values
>>> list1.append(a) # Append the first
>>> list2.append(b) # Append the second
>>> list1
[[1, 2, 3]]
>>> list2
[[4, 5, 6]]
>>>
読みやすく、効率的です。