2017-01-05 5 views
1

ポイントのリストをto/fromタプルのリストに変換するコードを書きましたが、あまり効率的ではありません。ポイントのリストをPythonのタプルのリストに変換する

誰かがこれをより簡潔にするための提案があったのだろうかと思いましたか?

from_point, to_point = None, None 
point_list = [] 

for p in [1, 5, 2, 4, 7, 9]: 
    to_point = p 
    if from_point and to_point: 
     point_list.append((from_point, to_point)) 
    from_point = to_point 

print(point_list) 

入力:[1, 5, 2, 4, 7, 9]

出力:[(1, 5), (5, 2), (2, 4), (4, 7), (7, 9)]

編集:変更されたポイントは、非シーケンシャルことにします。

+2

は、なぜあなたはfrom_pointとto_point'場合 'テストするのですか? –

+0

@WillemVanOnsem point_listに追加する前にポイントを有効/無効にするにはこれがなければ、最初のポイントは(なし、5) – desiguel

答えて

2

あなたはいつもzipを使用することができます。これについて

>>> p = [1, 5, 2, 4, 7, 9] 
>>> point_list = list(zip(p[:-1], p[1:])) 
>>> print(point_list) 
[(1, 5), (5, 2), (2, 4), (4, 7), (7, 9)] 
+0

ああ、それはタイトです!ありがとう! – desiguel

+1

私たちは効率を重視しているので、リストスライスの代わりに 'itertools.islice'を使うのが一番良いでしょう。 –

0

代替一行ソリューション

input = [1, 2, 3, 4, 5, 6] 
output = [(input[index], input[index+1]) for index in range(len(list)-1)] 
print(output) 
0

import more_itertools as mit 

list(mit.pairwise([1, 5, 2, 4, 7, 9])) 
# [(1, 5), (5, 2), (2, 4), (4, 7), (7, 9)] 
関連する問題