1

どう質問したらいいのかよくわかりませんし、プログラミングの経験もあまりないので、ご容赦ください。とにかく、私には問題があります。基本的に、いくつかの数値の合計と平均を計算する必要があります。

The program is supposed to have the user inputs values. They input a month and a number associated with that month, and then I need to get the average. So I have one big list, and then lists within that list. It basically looks like this:

    months = [["January", 3.45], ["February", 7.1865], ["March", 4.56]]

What I'm wondering is, how do I single out the second element in each list? I was thinking that I could use a for loop and compiling the numbers into a separate list, but I tried that and I couldn't it to calculate correctly.

4

6 に答える 6

6

これはまだ誰も言っていません。

sum(x[1] for x in monthlist)

以下のコメントで述べたように、 の各要素monthlistが反復可能であり、正確に 2 つの要素を持っていることがわかっている場合は、タプルをアンパックすることでこれをもう少し明確にすることができます。

sum(value for month,value in monthlist)

これは、合計に渡すためだけに中間リストを作成しません。それが発電機の美しさです。ここでの本当の美しさは、 monthlist がある種の遅延イテレータ (ファイル オブジェクトなど) である場合です。次に、一度に複数の要素をメモリに保存せずに合計できます。

#code to sum the first column from a file:
with open(file) as f:
    first_col_sum = sum(float(line.split()[0]) for line in f)
于 2012-11-09T02:49:20.057 に答える
6

これをコメントではなく回答にすることもできます。このzip関数は、一致する要素を組み合わせて、ジッパーのように機能します。

>>> zip([1,2,3],[4,5,6])
<zip object at 0xb6e5beec>
>>> list(zip([1,2,3],[4,5,6]))
[(1, 4), (2, 5), (3, 6)]

そして、基本的に f(*[a,b]) を f(a,b) に変換する * 演算子を使用すると、逆方向に進むことができます。

>>> list(zip(*(zip([1,2,3],[4,5,6]))))
[(1, 2, 3), (4, 5, 6)]

したがってzip、リストを分割するために使用できます。

>>> list(zip(*months))
[('January', 'February', 'March'), (3.45, 7.1865, 4.56)]
>>> monthnames, numbers = zip(*months)
>>> monthnames
('January', 'February', 'March')
>>> numbers
(3.45, 7.1865, 4.56)

そのうちの 1 つだけを気にする場合、これは少し効率が悪くなりますが、慣れておくと便利なイディオムです。

于 2012-11-09T02:51:23.233 に答える
5

ここでリスト内包表記が役立ちます。

names = [item[0] for item in months]
numbers = [item[1] for item in months]

for単純なループだけを使用している場合、事態はさらに厄介になります。

names = []
numbers = []

for item in months:
    names.append(item[0])
    numbers.append(item[1])
于 2012-11-09T02:40:36.160 に答える
3

各リストの 2 番目の要素を抽出するには:

numbers = [i[1] for i in months]

すべての数値の合計を取得する場合:

numbersum = sum(numbers)
于 2012-11-09T02:40:34.767 に答える
1

itemgetter のもう1 つのオプション:

from operator import itemgetter

months = [["January", 3.45], ["February", 7.1865], ["March", 4.56]]
sum(map(itemgetter(1), months)) # what means sum all items where each item is retrieved from month using index 1
于 2012-11-09T02:44:23.513 に答える
0

まだ見てないので追加。

>>> map(None,*months)
[('January', 'February', 'March'), (3.4500000000000002, 7.1864999999999997, 4.5599999999999996)]

map(None, *months)[1]あなたが求めるリストもそうです。

于 2012-11-09T03:21:04.653 に答える