Python 2での拡張タプルの開梱
-
26-10-2019 - |
質問
Python 2で拡張タプルの開梱をシミュレートすることは可能ですか?
具体的には、ループ用を持っています。
for a, b, c in mylist:
MyListがサイズ3のタプルのリストである場合、これは正常に機能します。サイズ4のリストを渡すと、ループが機能する場合も同じです。
私は名前が付けられたタプルを使用することになると思いますが、簡単に書く方法があるのではないかと思っていました。
for a, b, c, *d in mylist:
となることによって d
余分なメンバーを食べる。
解決
リストを4タプルに変換するラッパー関数を定義できます。例えば:
def wrapper(thelist):
for item in thelist:
yield(item[0], item[1], item[2], item[3:])
mylist = [(1,2,3,4), (5,6,7,8)]
for a, b, c, d in wrapper(mylist):
print a, b, c, d
コード印刷:
1 2 3 (4,)
5 6 7 (8,)
他のヒント
あなたはそれを直接することはできませんが、これを行うためにユーティリティ関数を書くことはそれほど難しくありません:
>>> def unpack_list(a, b, c, *d):
... return a, b, c, d
...
>>> unpack_list(*range(100))
(0, 1, 2, (3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99))
あなたはそれをこのようにあなたのforループに適用することができます:
for sub_list in mylist:
a, b, c, d = unpack_list(*sub_list)
それのために、いくつかの要素を解消するために一般化されています:
lst = [(1, 2, 3, 4, 5), (6, 7, 8), (9, 10, 11, 12)]
def unpack(seq, n=2):
for row in seq:
yield [e for e in row[:n]] + [row[n:]]
for a, rest in unpack(lst, 1):
pass
for a, b, rest in unpack(lst, 2):
pass
for a, b, c, rest in unpack(lst, 3):
pass
Python3拡張開梱とまったく同じ機能を持つ非常に基本的な機能を記述できます。読みやすさのためにわずかに冗長です。 「休息」は、アスタリスクがどこにあるかの位置であることに注意してください(最初の位置1ではなく、0ではなく)
def extended_unpack(seq, n=3, rest=3):
res = []; cur = 0
lrest = len(seq) - (n - 1) # length of 'rest' of sequence
while (cur < len(seq)):
if (cur != rest): # if I am not where I should leave the rest
res.append(seq[cur]) # append current element to result
else: # if I need to leave the rest
res.append(seq[cur : lrest + cur]) # leave the rest
cur = cur + lrest - 1 # current index movded to include rest
cur = cur + 1 # update current position
return(res)
所属していません StackOverflow