LoginSignup
0
0

More than 5 years have passed since last update.

python3.4 unpacking lists and tuplesメモ

Last updated at Posted at 2016-01-04

date, name, price = ['December 23, 2015', 'Bread Gloves', '8.51']とするとそれぞれの変数に引き渡すことが出来るが、変数の数とリストの中身が同じ個数でないとエラーを吐き出してしまう。

そこでfirst, *middle, lastの出番

def drop_first_last(grades):
    first, *middle, last = grades 
    # take the first item in "first", take all of them in the middle in "middle", the last goes in "last"
    avg = sum(middle) / len(middle)
    print(avg)

drop_first_last([65, 76, 98, 54, 21])
drop_first_last([65, 76, 98, 54, 45, 23, 97, 39, 86, 21])

こんな感じでmiddleが中間にあるものを全て引き取ってくれる。

zipを使ってみる

zipを使うことによって使うことによってタプルの中に入ってる単語同士をくっつけたりすることが出来る。

first = ['Bucky', 'Tom', 'Taylor']
last = ['Roberts', 'Hanks', 'Swift']
# it would be kwl to tie each other together
# this is where zip method comes in

そこで

names = zip(first, last)
#zip ties them together and throw it in a tuple called "names"
# i.g. [('Bucky', 'Roberts'), ('Tom', 'Hanks'), ('Taylor', 'Swift')]...
for a, b in names:
    print(a, b)

"""
Bucky Roberts
Tom Hanks
Taylor Swift
"""

minとmaxも加えてみる

解説動画を参考に以下の様な感じにまとめてみた。

stocks = {
    'GOOG': 520.54,
    'FB': 76.45,
    'YHOO': 39.28,
    'AMZN': 306.21,
    'AAPL': 99.76
}


print(min(zip(stocks.values(), stocks.keys()))) #(39.28, 'YHOO')
# the item or the list that youve thrown first is how its gonna sort it by
# if you put names first = alphabetical order
# if you put numbers first = numerical order

print(max(zip(stocks.values(), stocks.keys()))) #(520.54, 'GOOG')

print(sorted(zip(stocks.values(), stocks.keys()))) #[(39.28, 'YHOO'), (76.45, 'FB'), (99.76, 'AAPL'), (306.21, 'AMZN'), (520.54, 'GOOG')]
print(sorted(zip(stocks.keys(), stocks.values()))) #[('AAPL', 99.76), ('AMZN', 306.21), ('FB', 76.45), ('GOOG', 520.54), ('YHOO', 39.28)]
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0