2012-05-24 15 views

答えて

36

使用のzipあなたは両方の

>>> r=(1,'one'),(2,'two'),(3,'three') 
>>> zip(*r) 
[(1, 2, 3), ('one', 'two', 'three')] 
+0

これはPython 3で動作しますか? – bourbaki4481472

+2

@ bourbaki4481472はい、Python 3で:list(zip(* r)) –

30
>>> tl = [(1,'one'),(2,'two'),(3,'three')] 
>>> [item[0] for item in tl] 
[1, 2, 3] 
10
>>> mylist = [(1,'one'),(2,'two'),(3,'three')] 
>>> [j for i,j in mylist] 
['one', 'two', 'three'] 
>>> [i for i,j in mylist] 
[1, 2, 3] 

[(1,'one'),(2,'two'),(3,'three')] 

返されたリストには次のようになります。したがって、mylistの要素を反復し、タプルの2つの要素に順番に、ijを設定します。それが効果的に等価です:

>>> newlist = [] 
>>> for i, j in mylist: 
...  newlist.append(i) 
... 
>>> newlist 
[1, 2, 3] 
+0

あなたは説明できますか? – user1413824

+0

それは[list comprehension]です(http://docs.python.org/tutorial/datastructures.html#list-comprehensions) –

+0

@ user1413824 - それを少し説明するために更新しました:) – fraxel

0

が必要な場合は、あまりにもこれを試すことができます。..

dict(my_list).keys() 
関連する問題